将 xml 元素从 xml 文档插入到另一个 xml 文档

发布于 2024-09-28 10:46:58 字数 541 浏览 0 评论 0原文

假设我必须使用 xml 文档:

<first_root>
  <element1/>
  <element2>
    <embedded_element/>
  </element2>
</first_root>

如何

<foo>
  <bar/>
</foo>

使用 php 和 DomDocument 或 SimpleXML 将第二个 xml 文档放入第一个文档中?

我希望它看起来像这样:

<first_root>
  <element1/>
  <element2>
    <foo>
      <bar/>
    </foo>
    <embedded_element/>
  </element2>
</first_root>

Let's say I have to xml documents:

<first_root>
  <element1/>
  <element2>
    <embedded_element/>
  </element2>
</first_root>

and

<foo>
  <bar/>
</foo>

How can I put this second xml doc into the first one, using php and DomDocument or SimpleXML?

I want it to look like something like this:

<first_root>
  <element1/>
  <element2>
    <foo>
      <bar/>
    </foo>
    <embedded_element/>
  </element2>
</first_root>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光病人 2024-10-05 10:46:58

您可以使用 DOMDocument 来完成此操作:

<?php

$aDoc = DOMDocument::loadXML('<?xml version="1.0" encoding="UTF-8" ?>
<first_root>
  <element1/>
  <element2>
    <embedded_element/>
  </element2>
</first_root>');

$bDoc = DOMDocument::loadXML('<?xml version="1.0" encoding="UTF-8" ?>
<foo>
  <bar/>
</foo>');

$aEmbeddedElement = $aDoc->getElementsByTagName('embedded_element')->item(0);

$bFoo = $bDoc->documentElement;

$aImportedFoo = $aDoc->importNode($bFoo,true);

$aEmbeddedElement->insertBefore($aImportedFoo);

echo $aDoc->saveXML();
?>

这里我将 XML 导入到 DOMDocument 中,然后选取第一个 embedded_element 出现和 foo 节点。在您必须深度导入foo到第一个文档中之后。现在您可以在 embedded_element 之前插入 foo

显然这只是一个令人高兴的情况......

文档: DOM

与 < code>SimpleXML 您可以通过基于前两个文档构建第三个文档来实现此目的,因为您无法将 SimpleXMLElements 附加到其他文档中。 (或者也许你可以,但有些东西我没有得到)

You can do it using DOMDocument:

<?php

$aDoc = DOMDocument::loadXML('<?xml version="1.0" encoding="UTF-8" ?>
<first_root>
  <element1/>
  <element2>
    <embedded_element/>
  </element2>
</first_root>');

$bDoc = DOMDocument::loadXML('<?xml version="1.0" encoding="UTF-8" ?>
<foo>
  <bar/>
</foo>');

$aEmbeddedElement = $aDoc->getElementsByTagName('embedded_element')->item(0);

$bFoo = $bDoc->documentElement;

$aImportedFoo = $aDoc->importNode($bFoo,true);

$aEmbeddedElement->insertBefore($aImportedFoo);

echo $aDoc->saveXML();
?>

Here I imported the XML into DOMDocuments, then I picked up the first embedded_element occurrence and foo node. After you have to import deeply foo into the first document. Now you can insert foo before embedded_element.

Obviously this is only the happy case...

Documentation: DOM

With SimpleXML you can accomplish this by building a third document based on the first two because you can't append SimpleXMLElements into others. (Or maybe you can but there's something I didn't get)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文