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 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流