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


How Can I access direct to a child node in order to update/remove?

我有一个这样的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->number而不正确,echo $x->name为空,if为假。

    $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);
    }
}

对我来说是工作.

<?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();