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

使用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

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
        );
    }
}