【问题标题】:xml.etree.ElementTree - Trouble setting xmlns = '...'xml.etree.ElementTree - 设置 xmlns = '...' 时遇到问题
【发布时间】:2014-10-03 06:11:11
【问题描述】:

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

例子:

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

【问题讨论】:

    标签: python xml namespaces elementtree


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-01
      • 2021-06-19
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多