将child插入保存为String的XML

时间:2017-04-06 22:10:46

标签: php xml php-5.6

我在PHP工作,我有一个保存在String中的大型XML,我想作为第一个子节点插入一个节点,我知道父节点的名称,如下所示:

<mytag Someattributte="anything">
   here I want to put my tag
...
a lot of tags
...
</mytag>

我该怎么做?

1 个答案:

答案 0 :(得分:0)

使用DOM,您可以使用Xpath来获取节点,使用DOM文档方法创建新节点(DOMDocument::createDocumentFragment()),使用DOM节点方法来插入/追加它们(DOMDocument::insertBefore())。

文档片段是一种结构,允许您将节点列表视为单个节点。他们可以加载XML片段字符串。

$targetXml = <<<'XML'
<mytag Someattribute="anything">
   here I want to put my tag
...
a lot of tags
...
</mytag>
XML;

$fragmentXml = <<<'XML'
<othertag>with text</othertag>
XML;

$document = new DOMDocument();
$document->loadXml($targetXml);
$xpath = new DOMXpath($document);

// fetch the first mytag node that has a Someattribute
foreach ($xpath->evaluate('//mytag[@Someattribute][1]') as $targetNode) {
  // create a new fragment
  $fragment = $document->createDocumentFragment();
  // append the stored xml string to the fragment node
  $fragment->appendXml($fragmentXml);
  // insert the fragment before the first child of the target node
  $targetNode->insertBefore($fragment, $targetNode->firstChild);
}

echo $document->saveXml();

输出:

<?xml version="1.0"?>
<mytag Someattribute="anything"><othertag>with text</othertag>
   here I want to put my tag
...
a lot of tags
...
</mytag>

如果XML字符串是整个文档,则需要将其作为单独的文档实例加载并导入文档元素。

foreach ($xpath->evaluate('//mytag[@Someattribute][1]') as $targetNode) {
  $import = new DOMDocument();
  $import->loadXml($fragmentXml);
  $targetNode->insertBefore(
    $document->importNode($import->documentElement, TRUE),
    $targetNode->firstChild
  );
}