使用 Python minidom 解析 xml

我正在尝试使用 Python minidom 库解析 .xml 文件中的元素,但它似乎不起作用。它返回“IndexError 列表超出范围”。也许我在工作中使用了不正确的方法/库。请建议如何做到这一点。谢谢


from xml.dom import minidom

doc = minidom.parse('/path/to/file/runParameters.xml')

docs = doc.getElementsByTagName('RunParameters')

for el in docs:

    cloud = el.getElementsByTagName("EnableCloud")

    print(cloud[0].firstChild.nodeValue)

这是文件的结构


<?xml version="1.0"?>

<RunParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <EnableCloud>false</EnableCloud>

  <RunParametersVersion>MiSeq</RunParametersVersion>

  <CopyManifests>true</CopyManifests>

  <FlowcellRFIDTag>

    <SerialNumber>000000000-AG01C</SerialNumber>

    <PartNumber>17772</PartNumber>

    <ExpirationDate>2016-04-10T00:00:00</ExpirationDate>

  </FlowcellRFIDTag>

</RunParameters>


拉丁的传说
浏览 103回答 2
2回答

心有法竹

使用元素树import xml.etree.ElementTree as ETxml = '''<?xml version="1.0"?><RunParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <EnableCloud>false</EnableCloud>  <RunParametersVersion>MiSeq</RunParametersVersion>  <CopyManifests>true</CopyManifests>  <FlowcellRFIDTag>    <SerialNumber>000000000-AG01C</SerialNumber>    <PartNumber>17772</PartNumber>    <ExpirationDate>2016-04-10T00:00:00</ExpirationDate>  </FlowcellRFIDTag></RunParameters>'''root = ET.fromstring(xml)print(root.find('.//EnableCloud').text)输出false

侃侃尔雅

这段代码对我有用。请在您的系统上尝试:xx = '''<?xml version="1.0"?><RunParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">&nbsp; <EnableCloud>false</EnableCloud>&nbsp; <RunParametersVersion>MiSeq</RunParametersVersion>&nbsp; <CopyManifests>true</CopyManifests>&nbsp; <FlowcellRFIDTag>&nbsp; &nbsp; <SerialNumber>000000000-AG01C</SerialNumber>&nbsp; &nbsp; <PartNumber>17772</PartNumber>&nbsp; &nbsp; <ExpirationDate>2016-04-10T00:00:00</ExpirationDate>&nbsp; </FlowcellRFIDTag></RunParameters>'''.strip()with open('test2.xml','w') as f:&nbsp; &nbsp;f.write(xx)&nbsp; &nbsp;from xml.dom import minidomdoc = minidom.parse('test2.xml')docs = doc.getElementsByTagName('RunParameters')for el in docs:&nbsp; &nbsp; cloud = el.getElementsByTagName("EnableCloud")&nbsp; &nbsp; print(cloud[0].firstChild.nodeValue)输出false
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python