如何直接访问子节点以进行更新/删除?

时间:2013-10-01 16:04:33

标签: php xml dom

我有一个像这样的xml文件:

<participants>
  <participant>
    <number>1</number>
    <name>toto</name>
  </participant>
  <participant>
    <number>2</number>
    <name>titi</titi>
  </participant>
  <participant>
    <number>3</number>
    <name>tata</titi>
  </participant>
</participants>

我有一些参与者,并希望直接访问节点以更新或删除它。

问题是$x不正确,因为echo $x->numberecho $x->name为空,而if为false。

    $x = $participant->item($number);

    echo 'number = '.$x->number;
    echo 'name = '.$x->name;

请帮忙。感谢。

$number=2;
if ($xml = file_get_contents($file)) 
{
    $xmldoc = new DOMDocument('1.0', 'utf-8');
    $xmldoc->loadXML($xml, LIBXML_NOBLANKS);

    // find the participants tag
    $root = $xmldoc->getElementsByTagName('participants')->item(0);

    // get the list of participant node
    $participant = $xmldoc->getElementsByTagName('participant') ; 
    echo $participant->length; // I have a good number of participant node

            // get the node with the number i want
    $x = $participant->item($number);

    echo 'number = '.$x->number;
    echo 'name = '.$x->name;

    if ($x->number == $number) {
        echo "remove";
        $participant.removeChild($x);
    }
}

1 个答案:

答案 0 :(得分:0)

这对我有用。

<?php
$number=2;
if ($xml = file_get_contents("a.xml")) 
{
    $xmldoc = new DOMDocument('1.0', 'utf-8');
    $xmldoc->loadXML($xml, LIBXML_NOBLANKS);

    // find the participants tag
    $root = $xmldoc->getElementsByTagName('participants')->item(0);

    // get the list of participant node
    $participant = $xmldoc->getElementsByTagName('participant'); 
    $participant->length; // I have a good number of participant node

            // get the node with the number i want
    $name_get = $participant->item($number-1)->getElementsByTagName('number')->item(0)->nodeValue;
    $number_get = $participant->item($number-1)->getElementsByTagName('number')->item(0)->nodeValue;

    echo 'number = '.$name_get;
    echo 'name = '.$number_get;

    if ($number_get == $number) {
        echo "remove";
        $removing_node = $participant->item($number_get-1);
        $root->removeChild($removing_node);
    }
}
echo $xmldoc->saveXML();