我有一个XML文档,并希望使用SimpleXML在特定位置插入新节点。使用SimpleXML添加子节点
原始XML是这样的:
<epp
xmlns="urn:ietf:params:xml:ns:epp-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:ietf:params:xml:ns:epp-1.0 epp-1.0.xsd"
>
<command>
<create>
<domain:create
xmlns:domain="urn:ietf:params:xml:ns:domain-1.0"
xsi:schemaLocation="urn:ietf:params:xml:ns:domain-1.0 domain-1.0.xsd"
>
<domain:period unit="y"></domain:period>
</domain:create>
</create>
</command>
</epp>
<domain:create>
我需要添加以下节点后:
<domain:ns>
<domain:hostAttr>
<domain:hostName></domain:hostName>
<domain:hostAddr ip="v4"></domain:hostAddr>
</domain:hostAttr>
</domain:ns>
我怎么能这样做?我曾经尝试这样做:
$xmlObj = simplexml_load_file('myXMLFile.xml');
$nsNode = $xmlObj->command->create->children(self::OBJ_URI_DOMAIN)->create->addChild('domain:ns');
$hostAttr = $nsNode->addChild('domain:hostAttr');
$hostName = $hostAttr->addChild('domain:hostName');
$hostAddr = $hostAttr->addChild('domain:hostAddr');
$hostAddr->addAtribute('ip', 'v4');
在此第一线,我得到这样的警告:
Warning: SimpleXMLElement::addChild() [simplexmlelement.addchild]: Cannot add child. Parent is not a permanent member of the XML tree
在第二行,也正因为如此,我越来越:
Fatal error: Call to a member function addChild() on a non-object
在此先感谢。其他说明: - php版本高于5.1; - 我以后在这个相同的XML上成功添加了子节点。
看起来像http://www.sitepoint.com/forums/showthread.php?p=4665410 – Tomalak 2010-08-05 09:34:27
的副本这是我绝望的程度。 :(对不起,我认为他们是无关的。:s你可以删除,如果你认为它更合适。 – MEM 2010-08-05 09:39:55
没关系,我刚刚在谷歌搜索过程中发现该错误消息的帖子,让我们看看需要多长时间一个解决方案。:) – Tomalak 2010-08-05 09:44:37