douniangliao4327
douniangliao4327
2010-10-14 11:29

从xml文件中删除节点

已采纳

I have an xml file

<?xml version="1.0"?>
<category>
  <name>SWEATERS</name>
  <name>WATCHES</name>
  <name>PANTS</name>
  <name>test</name>
  <name>1</name>
</category>

How i can remove the node <name>test</name> using xpath ,xquery and php. I used this code

 $name='test;
    $xmlfile="config/shop_categories.xml";
    $xml = simplexml_load_file($xmlfile);
    $target = $xml->xpath('/category[name="'.trim($name).'"]');
    print_r($target[0]);
    if($target == false)
    return; 
    $domRef = dom_import_simplexml($target[0]); //Select position 0 in XPath array
    $domRef->parentNode->removeChild($domRef);
    $dom = new DOMDocument('1.0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($xml->asXML());
    $dom->save($xmlfile);

But it is not working.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douzhuangna6906 douzhuangna6906 11年前

    Pretty sure this is a duplicate, but am too lazy to find it. Here you go:

    $xml = <<< XML
    <?xml version="1.0"?>
    <category>
      <name>SWEATERS</name>
      <name>WATCHES</name>
      <name>PANTS</name>
      <name>test</name>
      <name>1</name>
    </category>
    XML;
    
    $dom = new DOMDocument;
    $dom->loadXML($xml);
    $xPath = new DOMXPath($dom);
    foreach($xPath->query('//name[text() = "test"]') as $node) {
        $node->parentNode->removeChild($node);
    }
    echo $dom->saveXML();
    

    Output:

    <?xml version="1.0"?>
    <category>
      <name>SWEATERS</name>
      <name>WATCHES</name>
      <name>PANTS</name>
    
      <name>1</name>
    </category>
    
    点赞 评论 复制链接分享