【问题标题】:How can I get XML prefix declarations from root element with lxml如何使用 lxml 从根元素获取 XML 前缀声明
【发布时间】:2015-01-31 19:07:24
【问题描述】:

test.xml:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns="http://example.com" xmlns:foo="http://example.com/bar">
  <foo:Child>yikes</foo:Child>
</Root>

test.py:

from lxml import objectify
root = objectify.fromstring(file('test.xml').read())
print root.attrib

输出:

{}

如何获取前缀声明? IE。类似:

{
  "xmlns": "http://example.com",
  "xmlns:foo": "http://example.com/bar"}

更新:

root.keys()root.items()root.values() 分别产生 [][]{}

【问题讨论】:

  • 你试过root.keys吗?根.项目()? root.values()?

标签: python xml lxml xml-namespaces objectify


【解决方案1】:

Element 对象有一个名为nsmap 的属性,其中包含元素上下文的所有已知命名空间。在tutorial中提到。

>>> root.nsmap
{None: "http://example.com", "foo": "http://example.com/bar"}

【讨论】:

    【解决方案2】:
    import xml.etree.ElementTree as ET
    tree = ET.parse("test.xml")
    root = tree.getroot()
    print(root.attrib)
    

    输出:

    {'xmlns':'http://example.com''xmlns:foo'='http://example.com/bar'}

    希望有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-07
      • 1970-01-01
      相关资源
      最近更新 更多