如何添加xml头到dom对象 [英] How to add xml header to dom object

查看:448
本文介绍了如何添加xml头到dom对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是Python的xml.dom.minidom,但我认为这个问题对于任何DOM解析器都是有效的。

I'm using Python's xml.dom.minidom but I think the question is valid for any DOM parser.

我的原始文件在开始:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

这似乎不是dom的一部分,所以当我做一些像dom.toxml ()结果字符串开头没有行。

This doesn't seem to be part of the dom, so when I do something like dom.toxml() the resulting string have not line at the beginning.

如何添加?

example outpupt:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Root xmlns:aid="http://xxxxxxxxxxxxxxxxxx">
<Section>BANDSAW BLADES</Section>
</Root>

希望清楚。

推荐答案


这似乎不是dom的一部分

This doesn't seem to be part of the dom

XML声明没有得到自己的节点,不,但是声明的属性在 Document 对象上可见:

The XML Declaration doesn't get a node of its own, no, but the properties declared in it are visible on the Document object:

>>> doc= minidom.parseString('<?xml version="1.0" encoding="utf-8" standalone="yes"?><a/>')
>>> doc.encoding
'utf-8'
>>> doc.standalone
True

序列化文档应该包括 standalone =yes声明的一部分,但 toxml()不。您可以考虑这个bug,但是实际上, toxml()方法并没有作出任何承诺,以适当的方式序列化XML声明。 (例如你没有得到编码,除非你特别要求它。)

Serialising the document should include the standalone="yes" part of the declaration, but toxml() doesn't. You could consider this a bug, perhaps, but really the toxml() method doesn't make any promises to serialise the XML declaration in an appropriate way. (eg you don't get an encoding unless you specifically ask for it either.)

你可以负责自己编写文件:

You could take charge of writing the document yourself:

xml= []
xml.append('<?xml version="1.0" encoding="utf-8" standalone="yes"?>')
for child in doc.childNodes:
    xml.append(child.toxml())

但是你真的需要XML声明吗?您正在使用默认版本和编码,并且由于您没有DOCTYPE,所以不能有外部定义的实体,因此文档本质上已经是独立的。根据 XML标准:如果没有外部标记声明,独立文件声明没有意义。在我看来,你可以安全地省略它。

but do you really need the XML Declaration here? You are using the default version and encoding, and since you have no DOCTYPE there can be no externally-defined entities, so the document is already standalone by nature. As per the XML standard: "if there are no external markup declarations, the standalone document declaration has no meaning". It seems to me you could safely omit it completely.

这篇关于如何添加xml头到dom对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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