1Up*_*1Up 3 python xml namespaces elementtree
我肯定错过了什么。我正在尝试设置 google 产品提要,但很难注册命名空间。
例子:
此处的路线:https : //support.google.com/merchants/answer/160589
尝试插入:
<rss version="2.0"
xmlns:g="http://base.google.com/ns/1.0">
Run Code Online (Sandbox Code Playgroud)
这是代码:
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
Run Code Online (Sandbox Code Playgroud)
代码运行后,一切都很好,但我们错过了 xmlns=
我发现在 php 中创建 XML 文档更容易,但我想我会尝试一下。我哪里错了?
关于这一点,也许有更合适的方法在 python 中执行此操作,而不是使用 etree?
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())
Run Code Online (Sandbox Code Playgroud)