xml.etree.ElementTree - Trouble setting xmlns = '…'

让人想犯罪 __ 提交于 2020-01-14 05:18:07

问题


I must be missing something. I'm attempting to set up a google product feed, but am having a hard time registering the namespace.

Example:

Directions here: https://support.google.com/merchants/answer/160589

Trying to insert:

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

This is the code:

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

After code is run, everything turns out fine, but we're missing the xmlns=

I find it easier to create XML docs in php, but I figured I'd give this a try. Where am I going wrong?

On that note, perhaps there is a more appropriate way to do this in python, not using etree?


回答1:


The API docs for ElementTree do not make working with namespaces very clear, but it's mostly straightforward. You need to wrap elements in QName(), and not put xmlns in your namespace argument.

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


来源:https://stackoverflow.com/questions/25225934/xml-etree-elementtree-trouble-setting-xmlns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!