使用 DOMdocument 在 XML 文件中附加元素? [英] use DOMdocument to append elements in a XML-file?
问题描述
每当我想创建 XML 文档时,我都会在 php 中使用 DOMdocument 类.
i'm using the DOMdocument class in php whenever i want to create a XML document.
但是如何打开 XML 文档并在 XML 文档中的现有元素之后添加元素?
but how could i open a XML document and add elements after an existing element in the XML document?
它是一个非常庞大的 XML 文档,因此最好考虑最有效的方法来做到这一点.
its a very huge XML-document so it would be great to consider the most efficient way to do this.
推荐答案
如果您坚持使用 DOMdocument,添加新节点就像获取对现有节点的引用、创建子节点,然后添加新节点一样简单给那些孩子.我在下面使用了 XPath,但任何返回 DOMNode 的方法都应该可以工作.需要记住的重要部分是,即使您获取了树的一部分,在内部它也是原始 DOMDocument 的一部分.
If you're sticking with DOMdocument, appending a new node is as simple as getting a reference to an existing node, creating child nodes, and then appending new nodes to those children. I've used XPath below, but any method that returns a DOMNode should work. The important part to remember is even though you've fetched a part of the tree, internally it's part of the original DOMDocument.
$xml = new DomDocument();
$xml->loadXml('<foo><baz><bar>Node Contents</bar></baz></foo>');
//grab a node
$xpath = new DOMXPath($xml);
$results = $xpath->query('/foo/baz');
$baz_node_of_xml = $results->item(0);
//create a new, free standing node
$new_node = $xml->createElement('foobazbar');
//create a new, freestanding text node
$text_node = $xml->createTextNode('The Quick Brown Fox');
//add our text node
$new_node->appendChild($text_node);
//append our new node to the node we pulled out
$baz_node_of_xml->appendChild($new_node);
//output original document. $baz_nod_of_xml is
//still considered part of the original $xml DomDocument
echo $xml->saveXML();
这篇关于使用 DOMdocument 在 XML 文件中附加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!