xml.etree.ElementTree-麻烦设置xmlns ='...' [英] xml.etree.ElementTree - Trouble setting xmlns = '...'

查看:322
本文介绍了xml.etree.ElementTree-麻烦设置xmlns ='...'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定很想念东西.我正在尝试设置Google产品Feed,但很难注册名称空间.

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

示例:

此处的路线: 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=

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

我发现用php创建XML文档更加容易,但是我想尝试一下.我要去哪里错了?

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

请注意,也许有更合适的方法可以在python中执行此操作,而不使用etree?

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

推荐答案

用于ElementTree的API文档并未十分清楚地使用名称空间,但是它非常简单.您需要将元素包装在QName()中,而不要将xmlns放在名称空间参数中.

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

这篇关于xml.etree.ElementTree-麻烦设置xmlns ='...'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆