我有一个XML,它有一个t:subscriptions
元素,该元素包含多个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
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"