如何在python中读取根XML标记 [英] How to read root XML tag in python
问题描述
我的问题来自另一个stackoverflow问题:-如何在Python中获取xml文件的根节点?
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 root == "root":
print 'something'
它不起作用,所以我认为我需要将 root转换为文本或类似的东西吗?我对Python很陌生。
it doesn't work, so I assume I need to convert 'root' to text or something like that? I am very new to Python.
推荐答案
root
是 Element
类。任何此类对象都将具有标签
属性。只需使用 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".
这篇关于如何在python中读取根XML标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!