1.名称属性

  1. # --------假设获取了根节点-------
  2. from xml.etree import ElementTree as ET
  3. # 下列是文本字符串
  4. content = """
  5. <data>
  6. <country name="Liechtenstein">
  7. <rank updated="yes">2</rank>
  8. <year>2023</year>
  9. <gdppc>141100</gdppc>
  10. <neighbor direction="E" name="Austria" />
  11. <neighbor direction="W" name="Switzerland" />
  12. </country>
  13. <country name="Panama">
  14. <rank updated="yes">69</rank>
  15. <year>2026</year>
  16. <gdppc>13600</gdppc>
  17. <neighbor direction="W" name="Costa Rica" />
  18. <neighbor direction="E" name="Colombia" />
  19. </country>
  20. </data>
  21. """
  22. # 直接从文本字符串,获取根节点
  23. root = ET.XML(content)
  24. # --------假设获取了根节点-------
  25. print(root.tag) #data

2.名称的内部的属性

  1. # --------假设获取了根节点-------
  2. from xml.etree import ElementTree as ET
  3. # 下列是文本字符串
  4. content = """
  5. <data name='123'>
  6. <country name="Liechtenstein">
  7. <rank updated="yes">2</rank>
  8. <year>2023</year>
  9. <gdppc>141100</gdppc>
  10. <neighbor direction="E" name="Austria" />
  11. <neighbor direction="W" name="Switzerland" />
  12. </country>
  13. <country name="Panama">
  14. <rank updated="yes">69</rank>
  15. <year>2026</year>
  16. <gdppc>13600</gdppc>
  17. <neighbor direction="W" name="Costa Rica" />
  18. <neighbor direction="E" name="Colombia" />
  19. </country>
  20. </data>
  21. """
  22. # 直接从文本字符串,获取根节点
  23. root = ET.XML(content)
  24. # --------假设获取了根节点-------
  25. print(root.attrib) #{'name':'123'}

3.名称的文本属性

  1. # --------假设获取了根节点-------
  2. from xml.etree import ElementTree as ET
  3. # 下列是文本字符串
  4. content = """
  5. <data name='123'>123</data>
  6. """
  7. # 直接从文本字符串,获取根节点
  8. root = ET.XML(content)
  9. # --------假设获取了根节点-------
  10. print(root.text) #123