首页 > 解决方案 > 在 Python 中获取根节点的属性(命名空间)

问题描述

我需要提取 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

任何建议表示赞赏。

标签: pythonxmlxml-namespaces

解决方案


这里(使用 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

推荐阅读