0

XMLドキュメントの数値に+1を追加しようとしていますが、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でなければなりません...私は何が間違っているのですか?

事前に助けて感謝してください:-)

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>";

削除すると、2秒$xpath2 = new DOMXPath($xml);は必要ありませんXPath

コードパッドの例

于 2012-10-09T11:08:20.970 に答える