【问题标题】:How to use Dom libray in Python如何在 Python 中使用 Com 库
【发布时间】:2021-08-26 14:04:05
【问题描述】:

大家好。我一直在尝试使用以下库在 python 中读取 xml 文件:xml.dom.minidom,由于某种原因,调试器告诉我 dom 无法识别。你知道我应该怎么做才能使用这个库,或者更好地把一个包含几个孩子的完整 xml 文件读入 python 吗?

谢谢!

【问题讨论】:

标签: python xml dom libraries


【解决方案1】:

链接:

Data for test_data.xml

Reference on how to use xml.dom.minidom

您可以使用xml.dom.minidom中的parse(filename_or_file, parser=None, bufsize=None)函数从xml文件中提取xml数据

test_data.xml的内容:

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank>1</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank>4</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank>68</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>

代码:

from xml.dom.minidom import parse
tree = parse('test_data.xml').documentElement
countries = tree.getElementsByTagName('country')
for country in countries:
    print(f"Country name: {country.getAttribute('name')}")
    rank = country.getElementsByTagName('rank')[0].childNodes[0].data
    neighbors = []
    for neighbor in country.getElementsByTagName('neighbor'):
        neighbors.append(dict(name=neighbor.getAttribute('name'), direction=neighbor.getAttribute('direction')))
    print(f"Country rank: {rank}")
    print(f"Neighbors: {neighbors}")
    print()

输出:

Country name: Liechtenstein
Country rank: 1
Neighbors: [{'name': 'Austria', 'direction': 'E'}, {'name': 'Switzerland', 'direction': 'W'}]

Country name: Singapore
Country rank: 4
Neighbors: [{'name': 'Malaysia', 'direction': 'N'}]

Country name: Panama
Country rank: 68
Neighbors: [{'name': 'Costa Rica', 'direction': 'W'}, {'name': 'Colombia', 'direction': 'E'}]

我更喜欢使用 xml.etree.ElementTree 来解析 xml 文件,因为我发现它比使用 xml.dom.minidom 更容易

Reference on how to use xml.etree.Elementree

【讨论】:

  • 谢谢!还有一个疑问,python不允许我使用dom,编译器不识别,怎么办?
  • 您能分享一下您是如何初始化 dom 的吗?
  • from xml.dom.minidom import parse, parseString def main(): doc = xml.dom.minidom.parse("sample.xml") print(doc) #print(doc.firstChild.标记名)
  • 因为你已经直接导入了解析函数,所以使用parse('sample.xml')而不是xml.dom.minidom.parse('sample.xml)
  • xml.dom.minidom.parse('sample.xml') 将在您的导入语句为 import xml 时起作用
猜你喜欢
  • 2016-12-21
  • 1970-01-01
  • 2012-03-09
  • 2014-10-05
  • 2014-09-13
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
相关资源
最近更新 更多