在Python中使用ElementTree发出名称空间规范

编程入门 行业动态 更新时间:2024-10-25 20:24:12
本文介绍了在Python中使用ElementTree发出名称空间规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图发出带有元素树的XML文件,其中包含XML声明和名称空间。这是我的示例代码:

I am trying to emit an XML file with element-tree that contains an XML declaration and namespaces. Here is my sample code:

from xml.etree import ElementTree as ET ET.register_namespace('com',"wwwpany") #some name # build a tree structure root = ET.Element("STUFF") body = ET.SubElement(root, "MORE_STUFF") body.text = "STUFF EVERYWHERE!" # wrap it in an ElementTree instance, and save as XML tree = ET.ElementTree(root) tree.write("page.xml", xml_declaration=True, method="xml" )

但是,两者都不<?xml 标记也不会出现,也不会显示任何名称空间/前缀信息。

However, neither the <?xml tag comes out nor any namespace/prefix information. I'm more than a little confused here.

推荐答案

尽管文档否则,我只能得到<?xml> 声明通过同时指定xml_declaration和编码。

Although the docs say otherwise, I only was able to get an <?xml> declaration by specifying both the xml_declaration and the encoding.

您必须在已注册的名称空间中声明节点,才能在文件中的节点上获得名称空间。这是代码的固定版本:

You have to declare nodes in the namespace you've registered to get the namespace on the nodes in the file. Here's a fixed version of your code:

from xml.etree import ElementTree as ET ET.register_namespace('com',"wwwpany") #some name # build a tree structure root = ET.Element("{wwwpany}STUFF") body = ET.SubElement(root, "{wwwpany}MORE_STUFF") body.text = "STUFF EVERYWHERE!" # wrap it in an ElementTree instance, and save as XML tree = ET.ElementTree(root) tree.write("page.xml", xml_declaration=True,encoding='utf-8', method="xml")

输出(page.xml)

Output (page.xml)

<?xml version='1.0' encoding='utf-8'?><com:STUFF xmlns:com="wwwpany"><com:MORE_STUFF>STUFF EVERYWHERE!</com:MORE_STUFF></com:STUFF>

ElementTree也不漂亮。这是输出精美的输出:

ElementTree doesn't pretty-print either. Here's pretty-printed output:

<?xml version='1.0' encoding='utf-8'?> <com:STUFF xmlns:com="wwwpany"> <com:MORE_STUFF>STUFF EVERYWHERE!</com:MORE_STUFF> </com:STUFF>

您也可以声明默认名称空间,并且不要t需要注册一个:

You can also declare a default namespace and don't need to register one:

from xml.etree import ElementTree as ET # build a tree structure root = ET.Element("{wwwpany}STUFF") body = ET.SubElement(root, "{wwwpany}MORE_STUFF") body.text = "STUFF EVERYWHERE!" # wrap it in an ElementTree instance, and save as XML tree = ET.ElementTree(root) tree.write("page.xml", xml_declaration=True,encoding='utf-8', method="xml",default_namespace='wwwpany')

输出(漂亮的打印间距是我的)

Output (pretty-print spacing is mine)

<?xml version='1.0' encoding='utf-8'?> <STUFF xmlns="wwwpany"> <MORE_STUFF>STUFF EVERYWHERE!</MORE_STUFF> </STUFF>

更多推荐

在Python中使用ElementTree发出名称空间规范

本文发布于:2023-11-16 21:14:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607487.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:名称   空间   Python   ElementTree

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!