gpt4 book ai didi

python - 遍历 XML?

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:40 28 4
gpt4 key购买 nike

使用 Python 浏览 XML 的最简单方法是什么?

<html>
<body>
<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:body>
<getservicebyidresponse xmlns="http://www.something.com/soa/2.0/SRIManagement">
<code xmlns="">
0
</code>
<client xmlns="">
<action xsi:nil="true">
</action>
<actionmode xsi:nil="true">
</actionmode>
<clientid>
405965216
</clientid>
<firstname xsi:nil="true">
</firstname>
<id xsi:nil="true">
</id>
<lastname>
Last Name
</lastname>
<role xsi:nil="true">
</role>
<state xsi:nil="true">
</state>
</client>
</getservicebyidresponse>
</soapenv:body>
</soapenv:envelope>
</body>
</html>

我会使用正则表达式并尝试获取我需要的行的值,但是有没有 pythonic 方式?像 xml[0][1] 之类的东西?

最佳答案

正如@deceze 已经指出的,您可以使用 xml.etree.ElementTree在这里。

import xml.etree.ElementTree as ET
tree = ET.parse("path_to_xml_file")
root = tree.getroot()

您可以遍历根的所有子节点:

for child in root.iter():
if child.tag == 'clientid':
print(child.tag, child.text.strip())

子节点是嵌套的,我们可以通过索引访问特定的子节点,所以 root[0][1] 应该可以工作(只要索引正确)。

关于python - 遍历 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42064006/

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