如何在Python中读取根XML标签

发布于 2024-12-05 11:57:35 字数 457 浏览 2 评论 0原文

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

My question follows on from another stackoverflow question:- "How to get the root node of an xml file in Python?"

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

When I extract and print the root tag, I receive:-

<Element 'root' at 0x1234abcd>

I then want to check that the root tag has a certain title, how do I pull out just the tag name?

If I try:

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

it doesn't work, so I assume I need to convert 'root' to text or something like that? I am very new to Python.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷离° 2024-12-12 11:57:35

您应该能够使用 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"

You should be able to use the tag function to get the name of the node.

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"
鹊巢 2024-12-12 11:57:35

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

root is an instance of the Element class. Any such object will have a tag attribute. Just use root.tag. Given what you say in your question, this should produce the string "root".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文