xml.etree.ElementTree - 麻烦设置xmlns ='...'

时间:2014-08-10 05:47:39

标签: python xml namespaces elementtree

我一定错过了什么。我尝试设置Google商品Feed,但是很难注册命名空间。

示例:

此处的说明:https://support.google.com/merchants/answer/160589

尝试插入:

<rss version="2.0" 
xmlns:g="http://base.google.com/ns/1.0">

这是代码:

from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

tree = ElementTree
tree.register_namespace('xmlns:g', 'http://base.google.com/ns/1.0')
top = tree.Element('top')
#... more code and stuff

代码运行后,一切都很好,但我们错过了xmlns=

我发现在php中创建XML文档更容易,但我想我试一试。我哪里错了?

就这一点而言,也许在python中有更合适的方法可以做到这一点,而不是使用etree?

1 个答案:

答案 0 :(得分:3)

ElementTree的API文档不能非常清楚地使用命名空间,但它大部分都是直截了当的。您需要在QName()中包装元素,而不是将xmlns放在命名空间参数中。

# Deal with confusion between ElementTree module and class name
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree, Element, SubElement, QName, tostring
from io import BytesIO

# Factored into a constant
GOOG = 'http://base.google.com/ns/1.0'
ET.register_namespace('g', GOOG)

# Make some elements
top = Element('top')
foo = SubElement(top, QName(GOOG, 'foo'))

# This is an alternate, seemingly inferior approach
# Documented here: http://effbot.org/zone/element-qnames.htm
# But not in the Python.org API docs as far as I can tell
bar = SubElement(top, '{http://base.google.com/ns/1.0}bar')

# Now it should output the namespace
print(tostring(top))

# But ElementTree.write() is the one that adds the xml declaration also
output = BytesIO()
ElementTree(top).write(output, xml_declaration=True)
print(output.getvalue())