gpt4 book ai didi

php - SimpleXML - 使用先前声明的命名空间添加新节点 - 如何?

转载 作者:行者123 更新时间:2023-12-04 16:51:43 24 4
gpt4 key购买 nike

我想为 <domain:create> 在一个非常具体的地方添加一个 child (所以我也使用 DOM 而不仅仅是 simpleXML)节点。

我试图在 simpleXML 构造上使用 $ns 属性。

$nsNode = new SimpleXMLElement('<domain:ns>', $options = 0, $ns='urn:ietf:params:xml:ns:domain-1.0');

//transform the target into dom object for manipulation
$nodeRegistrantDom = dom_import_simplexml($nodeRegistrant);

但我得到:

I/O warning : failed to load external entity "<domain:ns>"



我尝试在创建元素后注册前缀,
但在此之后我没有使用 xpath,所以这是一个非常无用的尝试......
//creates the simpleXML object node to be inserted.
$nsNode = new SimpleXMLElement('<ns/>');

//this will not work, because we will not use xpath after it :s
$nsNode->registerXPathNamespace('domain', 'urn:ietf:params:xml:ns:domain-1.0');

由于 xml 是从一个文件中加载的,并且该文件是这个 ns 声明的,也许我们应该从那个文件中获取它?

以下是对上述内容的总体介绍,以便我们更好地了解上下文:
我们正在加载一个包含整体结构的 XML 文件:
 $xmlObj = simplexml_load_file('EppCreateDomain.xml');

我们将抓取一个我们将用作目标的元素:
//grab the target.
$nodeRegistrant = $xmlObj->command->create->children(self::OBJ_URI_DOMAIN)->create->registrant;

//transform the target into a dom object for later manipulation
$nodeRegistrantDom = dom_import_simplexml($nodeRegistrant);

//we try to use simpleXML to create the node that we want to add after our target.
$nsNode = new SimpleXMLElement('<domain:ns>');


//grabs the node and all his children (none in this case), by importing the node we want to add,
//into the root object element that contains the <domain:registrant> node.
$nsNodeDom = $nodeRegistrantDom->ownerDocument->importNode(dom_import_simplexml($nsNode), true);

$nodeRegistrantDom->parentNode->insertBefore($nsNodeDom, $nodeRegistrantDom->nextSibling);

$simpleXmlNsNode = simplexml_import_dom($nsNodeDom);

现在我们将节点放置在适当的位置。
并转换为 simpleXML,因此,我们现在可以轻松添加一些子项并填充 xml 文件的其余部分。
$hostAttr = $simpleXmlNsNode->addChild('domain:hostAttr');
$hostName = $hostAttr->addChild('domain:hostName');

请指教,
内存力

最佳答案

Since the xml is loaded from a file, and that file as this ns declared, maybe we should grab it from that file?



如果该文件是 XML 文件,是的,您应该加载整个文件,而不仅仅是一部分。

声明命名空间后,添加命名空间元素很容易:
<?php
$xml = <<<XML
<epp>
<domain:create xmlns:domain="urn:someurn" xmlns:ietf="urn:thaturn">
<domain:name></domain:name>
<domain:registrant></domain:registrant>
<domain:contact></domain:contact>
</domain:create>
</epp>
XML;

$sxml = new SimpleXMLElement($xml);
$sxml->children("domain", true)->create->addChild("newElem", "value", "urn:thaturn");
echo $sxml->saveXML();


<?xml version="1.0"?>
<epp>
<domain:create xmlns:domain="urn:someurn" xmlns:ietf="urn:thaturn">
<domain:name/>
<domain:registrant/>
<domain:contact/>
<ietf:newElem>value</ietf:newElem></domain:create>
</epp>

关于php - SimpleXML - 使用先前声明的命名空间添加新节点 - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3438900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com