gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:20:51 24 4
gpt4 key购买 nike

我一定错过了什么。我正在尝试设置谷歌产品提要,但很难注册命名空间。

示例:

路线: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?

最佳答案

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

关于python - xml.etree.ElementTree - 设置 xmlns = '...' 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25225934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com