如何在片段创建中使用全局名称空间定义? [英] How to use global namespace definitions in a fragment creation?

查看:66
本文介绍了如何在片段创建中使用全局名称空间定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根元素具有名称空间声明,例如xmlns:xlink="http://www.w3.org/1999/xlink" ...,因此,任何附加节点(例如,由appendChild附加)都将接受该名称空间.我可以附加<graphic xlink:href=".."/>,因为总体上它是有效的...但是要附加一个片段,我首先需要使用createDocumentFragment()创建该片段.

The root element have namespace declarations like xmlns:xlink="http://www.w3.org/1999/xlink" ... so, any node appended (ex. by appendChild) will accept the namespace. I can append <graphic xlink:href=".."/> because on the whole it is valid... But to append a fragment I need first to create the fragment with createDocumentFragment().

示例:

    $tmp = $dom->createDocumentFragment();
    $ok = $tmp->appendXML('<graphic xlink:href="file123.ext"/>');

在运行时生成错误, DOMDocumentFragment::appendXML(): namespace error : Namespace prefix xlink for href on inline-graphic is not defined

when running, generates an error, DOMDocumentFragment::appendXML(): namespace error : Namespace prefix xlink for href on inline-graphic is not defined

如何对DOMDocumentFragment::appendXML()方法说使用DomDocument命名空间"?

How to say "use the DomDocument namespaces" to the DOMDocumentFragment::appendXML() method?

(已转移为答案,请不要在此处污染)

(transfered as an answer, to not polute here)

推荐答案

它似乎按照预期的方式工作.查看错误报告#44773 . chregu@php.net表示这不是错误,并且可以正常工作.尽管我会同意该错误报告和其他评论,但由于该片段是从DOMDocument生成的,并且已定义了名称空间,因此实际上应该知道它们是什么,并且应该可以正常工作.

It looks like it's working the way it's supposed to. Check out bug report #44773. chregu@php.net says it's not a bug and works properly. Though I would agree with the bug report and other comments, that since the fragment is made off of the DOMDocument, and it has the namespaces defined it should in fact know what they are and should work without problem.

将名称空间与元素一起传递.它不会显示在输出的XML中,但会被该片段读取,以便它可以创建属性而不会出现任何错误.

Pass the namespace in with the element. It won't show up in the XML that is output, but will be read by the fragment so that it can create the attribute without any errors.

$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('MyRoot');
$root->setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink');
$dom->appendChild($root);

$tmp = $dom->createDocumentFragment();
$ok = $tmp->appendXML('<graphic xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="file123.ext"/>');
$dom->documentElement->appendChild($tmp);
die($dom->saveXML());

输出

<?xml version="1.0" encoding="utf-8"?>
<MyRoot xmlns:xlink="http://www.w3.org/1999/xlink"><graphic xlink:href="file123.ext"/></MyRoot>

这篇关于如何在片段创建中使用全局名称空间定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆