0

我正在尝试将 +1 添加到我的 XML 文档中的数字,如果它只是一个没有问题,但是...如果我想更新 2 个节点,它会出错吗?

这是我尝试过的:

$xml = new DOMDocument("1.0", "ISO-8859-1");
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML('<?xml version="1.0"?>
<friends>
  <friend id="1">
    <name>MyTest</name>
    <games>5</games>
    <wins>3</wins>
  </friend>
</friends>');

echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";

$library = $xml->documentElement;
$xpath = new DOMXPath($xml);
$xpath2 = new DOMXPath($xml);

$result = $xpath->query('//friend[@id="1"]/games');
if($result){

    $cgames = $xpath->query('//friend[@id="1"]/games')->item(0);
    $cgames = $cgames->nodeValue;
    $result->item(0)->nodeValue = $cgames+1;

    $cwins = $xpath->query('//friend[@id="1"]/wins')->item(0);
    $cwins = $cwins->nodeValue;
    $result->item(0)->nodeValue = $cwins+1;

    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
}

这样做时,我只更新它的新值是 4?它应该是 6 应该是 4 ......我做错了什么?

请提前帮助和感谢:-)

4

1 回答 1

0

添加,因为您正在$result2尝试更新搜索/wins/games

$result = $xpath->query('//friend[@id="1"]/games');
$result2 = $xpath->query('//friend[@id="1"]/wins');

if($result){
    $cgames = $result->item(0)->nodeValue;
    $result->item(0)->nodeValue = $cgames+1;
}

if($result2){
    $cwins = $result2->item(0)->nodeValue;
    $result2->item(0)->nodeValue = $cwins+1;
}

echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";

并删除$xpath2 = new DOMXPath($xml);,你不需要 2 XPaths

键盘示例

于 2012-10-09T11:08:20.970 回答