【问题标题】:How to read root XML tag in python如何在python中读取根XML标签
【发布时间】:2011-09-19 00:43:35
【问题描述】:

我的问题来自另一个 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 很陌生。

【问题讨论】:

    标签: python xml elementtree


    【解决方案1】:

    您应该可以使用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"
    

    【讨论】:

    • 非常感谢,这么简单:),刚刚发现它不需要()标签后。再次感谢。
    【解决方案2】:

    rootElement 类的一个实例。任何此类对象都将具有tag 属性。只需使用root.tag。鉴于您在问题中所说的话,这应该会产生字符串“root”。

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 2017-06-28
      • 2018-08-04
      • 2018-08-03
      • 1970-01-01
      • 2018-01-19
      • 1970-01-01
      • 2015-07-19
      • 2021-09-03
      相关资源
      最近更新 更多