Php 选择xPath类型的第n个下一个同级
我需要的是在xml提要中搜索一个值,并根据该值更改同级的值 我有一个这样的结构Php 选择xPath类型的第n个下一个同级,php,xpath,Php,Xpath,我需要的是在xml提要中搜索一个值,并根据该值更改同级的值 我有一个这样的结构 <properties> <property name="sport"> <value>Football</value> </property> <property name="player"> <value>Lionel Messi</value> <
<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>
我以为这样应该行得通,但不知为什么不行,我也不知道为什么
$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
);
}
}
到目前为止,我知道问题出在$target
查询中,但我不知道有什么方法可以解决这个问题。我做错了什么
我刚刚收到一张白纸,一个晚上的睡眠为我提供了解决问题的见解。我忘了选择te项,因此有效的代码是
$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
);
}
}
您想从xPath中得到什么?我想替换
数组中出现
值的每个
元素的te值。
$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
);
}
}