gpt4 book ai didi

php - (PHP) 使用命名空间前缀附加新的 XML 子元素

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

我有一个带有 t:subscriptions 的 XML包含多个 t:subscription 的元素子元素。

我的主要目标是替换当前 t:subsciptions整体或全部t:subsciption带有新元素的元素。目前我已经创建了新的 t:subscription元素作为字符串(没有掌握 dom/simplexml 类,所以我不得不使用“回退”方法)。

现在我正在尝试通过 simplexml_load_string 将字符串转换为 XML,然后通过 dom_import_simplexml 以附加/替换 XML 中的当前订阅。我已经尝试了从这个站点找到的以下示例:

$newsubs = ''; //new XML as string

$sdom = new DOMDocument();
$sdom->loadXML($xml->asXML()); // current XML
//dpm($sdom->saveXML());
$xpath = new DOMXPath($sdom);

// ... x functions generate $newsubs string ...

$remove = $sdom->getElementsByTagName('subscriptions')->item(0); // get t:subscriptions for removal
$remove->parentNode->removeChild($remove); // remove t:subscriptions
$fragment = $sdom->createDocumentFragment();
$fragment->appendXml($newsubs);
$xpaths
->evaluate('//t:member') // this node holds t:subscriptions among others
->item(0) // there's always only one member node
->appendChild($fragment);
debug($sdom->saveXML());

到目前为止,我收到的唯一错误是 Namespace prefix X on Y is not defined这适用于所有元素。脚本删除命名空间前缀,尽管它们是在 xml 字符串中定义的,例如 <t:myelement>asdasd</t:myelement> .

将要添加此 XML 的 XML 文档已经带有前缀。我不明白为什么它不能接受带前缀的 XML 并去掉前缀,但新的 XML 会附加到文档中?没有意义。

最佳答案

该错误消息可能意味着 XML 中缺少命名空间的“xmlns:*”属性,或者命名空间前缀未在 XPath 对象上注册。

XML 文件

需要在两侧定义命名空间。第一个是 XML 本身。

<foo xmlns="urn:foo"/>

或者
<f:foo xmlns:f="urn:foo"/>

都由解析器解析为相同的命名空间和本地名称。您可以将元素名称读作 {urn:foo}:foo .

下面是 DOM 上的几个 *NS 方法,它们允许您使用命名空间。命名空间始终是 URN。前缀与匹配无关。
$node->getElementsByTagNameNS('urn:foo', 'foo')

前缀仅在需要作为值时才提供。例如创建一个使用它的元素节点。
$document->createElementNS('urn:foo', 'foo'); // no prefix 
$document->createElementNS('urn:foo', 'f:foo'); // with prefix "f"

路径

XPath 也在表达式中使用前缀。但它不应该从文档中读取它们。使用 DOMXpath::registerNamespace()为特定的命名空间注册自己的前缀。

例子

您的问题缺少完整的 XML,因此我将添加一个小的 Atom 示例。可以看到XML和PHP中的命名空间是一样的,只是前缀不同:
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom">
<atom:title>Example Feed</atom:title>
<atom:entry>
<atom:title>Atom-Powered Robots Run Amok</atom:title>
<atom:id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</atom:id>
</atom:entry>
</atom:feed>
XML;

$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$xpath->registerNamespace('a', 'http://www.w3.org/2005/Atom');

var_dump($xpath->evaluate('string(//a:entry/a:title)'));

输出:
string(28) "Atom-Powered Robots Run Amok"

关于php - (PHP) 使用命名空间前缀附加新的 XML 子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27402727/

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