【问题标题】:PHP/SimpleXML. How to add child to node returned by xpath?PHP/SimpleXML。如何将子节点添加到 xpath 返回的节点?
【发布时间】:2013-03-27 19:45:54
【问题描述】:

我有一个简单的 XML 字符串:

$sample = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');

我尝试使用 xpath() 查找节点并将子节点添加到该节点。

$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo $sample->asXML();

如您所见,child2 被添加为 child1 的子代,而不是 parent 的子代。

<root>
  <parent>
    <child1>
      <child2></child2>
    </child1>
  </parent>
</root>

但如果我更改我的 XML,addChild() 效果很好。这段代码

$sample = new SimpleXMLElement('<root><parent><child1><foobar></foobar></child1></parent></root>');
$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo $sample->asXML();

返回

<root>
  <parent>
    <child1>
      <foobar></foobar>
    </child1>
    <child2>
    </child2>
  </parent>
</root>

所以我有两个问题:

  1. 为什么?
  2. 如果child1 没有子级,我如何将child2 添加为parent 的子级?

【问题讨论】:

  • 您使用的是什么版本的 PHP 和 libxml2?您的“损坏”代码works for me
  • 在这种情况下,我提供的链接显示您的代码在 5.4.0 上适用于 2.7.8。
  • 我只能强调salathe 已经写过的内容:您问题中的原样代码确实有效。我也无法想象为什么会发生在你身上。您可能想在添加孩子之前先进行调试,例如:var_dump($node[0]-&gt;asXML());.

标签: php xpath simplexml addchild


【解决方案1】:

xpath() 返回传递给它的元素的 CHILDREN。所以,当你 addChild() 到 xpath() 返回的第一个元素时,你实际上是在向 parent 的第一个元素添加一个子元素,即 child1。当你运行这段代码时,你会看到它正在创建一个“parentChild”元素作为“parent”的子元素-

<?php
$original = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
$root = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
$parent = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
$child1 = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
$tXml = $original->asXML();
printf("tXML=[%s]\n",$tXml);
$rootChild = $root->xpath('//root');
$rootChild[0]->addChild('rootChild');
$tXml = $root->asXML();
printf("node[0]=[%s] tXML=[%s]\n",$rootChild[0],$tXml);
$parentChild = $parent->xpath('//parent');
$parentChild[0]->addChild('parentChild');
$tXml = $parent->asXML();
printf("node[0]=[%s] tXML=[%s]\n",$parentChild[0],$tXml);
$child1Child = $child1->xpath('//child1');
$child1Child[0]->addChild('child1Child');
$tXml = $child1->asXML();
printf("node[0]=[%s] tXML=[%s]\n",$child1Child[0],$tXml);
?>

tXML=[<?xml version="1.0"?>
<root><parent><child1/></parent></root>]
tXML=[<?xml version="1.0"?>
<root><parent><child1/></parent><rootChild/></root>]
tXML=[<?xml version="1.0"?>
<root><parent><child1/><parentChild/></parent></root>]
tXML=[<?xml version="1.0"?>
<root><parent><child1><child1Child/></child1></parent></root>]

【讨论】:

  • 只需检查您的parentChild。实际上它不是parent 的孩子,它是child1 的孩子。
猜你喜欢
  • 1970-01-01
  • 2012-11-30
  • 2011-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
相关资源
最近更新 更多