将数字添加到节点值并更新?

时间:2012-10-09 11:04:49

标签: php xml

我正在尝试在我的XML文档中为一个数字添加+1,如果它只是一个没有问题,但是...如果我想更新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 ......我做错了什么?

请提前帮助和感谢: - )

1 个答案:

答案 0 :(得分:0)

添加$result2,因为您尝试更新/wins搜索<{1}}

/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>"; ,您不需要2 $xpath2 = new DOMXPath($xml); s

Codepad Example