如何在Python中读取根XML标记

6

我的问题是跟随另一个stackoverflow的问题:「如何在Python中获取xml文件的根节点?」

from xml.etree import ElementTree as ET
path = 'C:\cool.xml'
et = ET.parse ( path )
root = et.getroot()

当我提取并打印根标签时,收到的结果为:-
<Element 'root' at 0x1234abcd>

我想检查根标签是否具有特定的标题,如何仅提取标签名称?

如果我尝试:

if root == "root":
    print 'something'

它不起作用,所以我认为我需要将 'root' 转换为文本或类似的东西?我对 Python 非常陌生。

2个回答

10
你应该使用tag函数来获取节点的名称。
from xml.etree import ElementTree as ET
path = 'C:\cool.xml'
et = ET.parse ( path )
root = et.getroot()

if root.tag == "root":
  print "I'm the root"

非常感谢,太简单了:),我发现标签后面不需要()。再次感谢。 - user788462

4

rootElement 类的一个实例。任何这样的对象都会有一个 tag 属性。只需使用 root.tag 即可。根据你在问题中所说的,这应该生成字符串 "root"。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接