1.名称属性
# --------假设获取了根节点-------
from xml.etree import ElementTree as ET
# 下列是文本字符串
content = """
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
"""
# 直接从文本字符串,获取根节点
root = ET.XML(content)
# --------假设获取了根节点-------
print(root.tag) #data
2.名称的内部的属性
# --------假设获取了根节点-------
from xml.etree import ElementTree as ET
# 下列是文本字符串
content = """
<data name='123'>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2023</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2026</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
</country>
</data>
"""
# 直接从文本字符串,获取根节点
root = ET.XML(content)
# --------假设获取了根节点-------
print(root.attrib) #{'name':'123'}
3.名称的文本属性
# --------假设获取了根节点-------
from xml.etree import ElementTree as ET
# 下列是文本字符串
content = """
<data name='123'>123</data>
"""
# 直接从文本字符串,获取根节点
root = ET.XML(content)
# --------假设获取了根节点-------
print(root.text) #123