如何在Python中读取根XML标签
我的问题源于另一个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用
tag
函数来获取节点的名称。You should be able to use the
tag
function to get the name of the node.root
是Element
类的实例。任何此类对象都将具有tag
属性。只需使用root.tag
。鉴于您在问题中所说的内容,这应该会产生字符串“root”。root
is an instance of theElement
class. Any such object will have atag
attribute. Just useroot.tag
. Given what you say in your question, this should produce the string "root".