gpt4 book ai didi

python - 在 Python 中解析 XML 字符串

转载 作者:太空狗 更新时间:2023-10-29 20:37:53 24 4
gpt4 key购买 nike

我有这个 XML 字符串结果,我需要获取标签之间的值。但是XML的数据类型是字符串。

  final = "  <Table><Claimable>false</Claimable><MinorRev>80601</MinorRev><Operation>530600 ION MILL</Operation><HTNum>162</HTNum><WaferEC>80318</WaferEC><HolderType>HACARR</HolderType><Job>167187008</Job></Table>

<Table><Claimable>false</Claimable><MinorRev>71115</MinorRev><Operation>530600 ION MILL</Operation><Experiment>6794</Experiment><HTNum>162</HTNum><WaferEC>71105</WaferEC><HolderType>HACARR</HolderType><Job>16799006</Job></Table> "

这是我的代码示例

root = ET.fromstring(final)
print root

这是我收到的错误:

xml.parsers.expat.ExpatError: The markup in the document following the root element must be well-formed.

我试过使用 ET.fromstring。但没有运气。

最佳答案

您的 XML 格式不正确。它必须只有一个顶级元素。 From Wikipedia :

Each XML document has exactly one single root element. It encloses all the other elements and is therefore the sole parent element to all the other elements. ROOT elements are also called PARENT elements.

尝试将其包含在附加标记中(例如 Tables),而不是使用 ET 进行解析:

xmlData = '''<Tables>
<Table><Claimable>false</Claimable><MinorRev>80601</MinorRev><Operation>530600 ION MILL</Operation><HTNum>162</HTNum><WaferEC>80318</WaferEC><HolderType>HACARR</HolderType><Job>167187008</Job></Table>
<Table><Claimable>false</Claimable><MinorRev>71115</MinorRev><Operation>530600 ION MILL</Operation><Experiment>6794</Experiment><HTNum>162</HTNum><WaferEC>71105</WaferEC><HolderType>HACARR</HolderType><Job>16799006</Job></Table>
</Tables>
'''

import xml.etree.ElementTree as ET
xml = ET.fromstring(xmlData)

for table in xml.getiterator('Table'):
for child in table:
print child.tag, child.text

自 Python 2.7 起 getiterator('Table') 应替换为 iter('Table') :

for table in xml.iter('Table'):
for child in table:
print child.tag, child.text

这会产生:

Claimable false
MinorRev 80601
Operation 530600 ION MILL
HTNum 162
WaferEC 80318
HolderType HACARR
Job 167187008
Claimable false
MinorRev 71115
Operation 530600 ION MILL
Experiment 6794
HTNum 162
WaferEC 71105
HolderType HACARR
Job 16799006

关于python - 在 Python 中解析 XML 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32494318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com