dsbruqxgt820011351 2015-10-23 19:20
浏览 117
已采纳

使用xPath选择第n个类型的下一个兄弟

What i need is to search a xml feed for a value and dependent on this value change a sibling's value.

I have a structure like this

<properties>
    <property name="sport">
        <value>Football</value>
    </property>
    <property name="player">
        <value>Lionel Messi</value>
    </property>
    <property name="nationality">
        <value>Argentine</value>
    </property>
    <property name="club">
        <value>FC Barcelona</value>
    </property>
    <property name="position">
        <value>Forward</value>
    </property>
</properties>

Now i know that some values might be incorrect or inconsistent so i made an array with the corrections, like so:

$position_replacements = Array(
    'Lionel Messi' => 'Center forward',
);

I assumed something like this should work, but somehow it doesn't and i don't know why..

$xml_src = 'players.xml';
$document = new DOMDocument();
$document->load($xml_src);
$xpath = new DOMXpath($document);

foreach($xpath->query('//property[@name="player"]') as $node){
    if(array_key_exists(trim($node->nodeValue), $position_replacements)){
        $target = $xpath->query('following-sibling::property[@name="position"]/value/text()', $node);
        $target->parentNode->replaceChild(
            $document->createTextNode($position_replacements[trim($node->textContent)]),
            $target
        );
    }
}

So far i know the problem is in the $target query, but i don't know any approach to solve this. What am i doing wrong?

I'm just getting a blanc page returned

  • 写回答

1条回答 默认 最新

  • dqcd84732 2015-10-24 09:12
    关注

    A night sleep provided me with the insights to solve it. I forgot to select te item, so the code that works is

    $xml_src = 'players.xml';
    $document = new DOMDocument();
    $document->load($xml_src);
    $xpath = new DOMXpath($document);
    
    foreach($xpath->query('//property[@name="player"]') as $node){
        if(array_key_exists(trim($node->nodeValue), $position_replacements)){
            $target = $xpath->query(
                'following-sibling::property/value/text()',
                $node->parentNode
            )->item(3);
            $target->parentNode->replaceChild(
                $document->createTextNode($position_replacements[trim($node->textContent)]),
                $target
            );
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?