【问题标题】:Getting root node's attributes (namespace) in Python在 Python 中获取根节点的属性(命名空间)
【发布时间】:2019-07-05 09:01:04
【问题描述】:

我需要提取xml文件开头的命名空间。

看起来像这样。

<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:a="CannotGetThisAttrib" xmlns:b="CannotGetThisAttrib">
<fileHeader c="CanGetThisAttrib/>>
<body></body>
<fooder/>
</root>

我可以提取根节点下的属性。但是,我无法获取根节点属性 a 和 b,它们是解析 xml 文件所必需的命名空间。

tree = ET.parse("xmlfile.xml")
root = tree.getroot()
root.attrib => None
root[0].attrib["c"] => CanGetThisAttrib

感谢任何建议。

【问题讨论】:

  • 这是内置的 ElementTree 还是来自 lxml 模块?另外,请修复示例 XML 中的语法错误。
  • 话虽如此,您的总体目标是什么/您要解决什么问题?
  • 我正在使用内置的 xml 模型。我正在尝试获取根标签属性的命名空间。 xml内置模块无法获取
  • 不,这不是你真正想要做的。 为什么你要获取命名空间?
  • 因为我需要它来获取根标签下的特定标签。每个标签在每个标签名称之前都有不同类型的命名空间

标签: python xml xml-namespaces


【解决方案1】:

这里(使用 lxml)

from lxml import etree

data = '''<?xml version="1.0" encoding="UTF-8"?>
           <root xmlns:a="CannotGetThisAttrib" xmlns:b="CannotGetThisAttrib">
            <fileHeader c="CanGetThisAttrib"/>
            <body></body>
            <fooder/>
         </root>
    '''

data = data.encode('ascii')
tree = etree.fromstring(data)
for k,v in tree.nsmap.items():
    print('{} -> {}'.format(k,v))

输出

a -> CannotGetThisAttrib
b -> CannotGetThisAttrib

【讨论】:

  • 我怀疑 OP 正在使用 lxml。
猜你喜欢
  • 2023-03-26
  • 1970-01-01
  • 2020-03-18
  • 2018-08-08
  • 2020-10-03
  • 2013-04-20
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
相关资源
最近更新 更多