xml.etree.ElementTree - 设置xmlns = '...' 时遇到问题。

3

我一定是漏掉了什么。我正在尝试设置一个Google产品源,但是在注册命名空间时遇到了困难。

例如:

请按照此处的说明进行操作: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个回答

6
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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接