如何可能将子节点添加到特定节点


How is possible add child to the specific node

这是我的起始xml:

 <?xml version="1.0" encoding="utf-8"?>
    <root>
      <child>
        <children></children>
     </child>
    </root>

我想在child中添加其他孩子??但我正在努力,但没有什么我不知道如何…:请帮忙,我想让我的xml喜欢这个

  <?xml version="1.0" encoding="utf-8"?>
    <root>
      <child>
        <children></children>
        <children></children>
     </child>
    </root>

这是我的代码:

<?php
            $dom = new DomDocument;
            //$dom->preserveWhiteSpace = FALSE;
            $dom->load("myXML.xml");
            $root = $dom->getElementById('root');
            $params = $dom->getElementsByTagName('child');
            $cantidadCategorias = $params->length+1;
            $newElement = $dom->createElement('child','');
            $dom->appendChild($newElement);
            $f = fopen("myXML.xml",'w+'); 
            fwrite($f,$dom->saveXML()); 
            fclose($f); 

有了DOMDocument,它就像这样简单:

$child = new DOMElement('children');
$parent->appendChild($child);

$parentDOMElement的父级,(在您更新问题后)获取该父级是您问题的一部分:

// append <children> to the first <child> element
$parent = $dom->getElementsByTagName('child')->item(0);
$child = new DOMElement('children');
$parent->appendChild($child);

由于您已经标记了php,我假设您正在寻找php解决方案你试过下面的吗:

$myxml = new SimpleXMLElement($xmlstr);
$myxml->child[0]->addChild('children');

请参阅:http://www.php.net/manual/en/simplexml.examples-basic.php有关PHP 中XML操作的一组好例子

关于如何附加XML节点的一些好例子可以在PHP手册中找到。就像这篇关于如何使用SimpleXMLElement类添加子节点的文章一样。