gpt4 book ai didi

python - 使用 Python 中的 xml 子对象、ElementTree

转载 作者:行者123 更新时间:2023-11-30 23:05:10 24 4
gpt4 key购买 nike

我正在使用一个程序生成的 xml 片段,该片段的标记很糟糕。我能够解析出我正在寻找的内容,但我认为它不是很Pythonic。该程序的目标是对totalLines 条目等进行总计。我正在使用 elementtree 来提取值。寻找有关简化语法的建议。

xml:

<?xml version="1.0"?>
<Status name="System Status">
<Bean name="SLMHandler" cn="com.open.eventCollector.OSLMHandler">
<Status name="SLF File manager for SODLC2">
<Prop name="totalLines">1105413065</Prop>
</Status>
</Bean>

<Bean name="ThreadPool" cn="com.open.util.OThreadPoolBean">
<Prop name="minThreads">5</Prop>
<Prop name="maxThreads">25</Prop>
<Prop name="checkedOutThreads">3</Prop>
<Prop name="availableThreads">2</Prop>
<Prop name="maxIdleTime">300000</Prop>
</Bean>

<Bean name="EventCollector" cn="com.open.eventCollector.OEventCollector">
<Prop name="numUnmatchedLines">785319</Prop>

<Status name="Adapters">

<Status name="Logfile_EpilogWin_Generic">
<Prop name="linesRead">0</Prop>
</Status>
</Status>
</Bean>

Python:

import xml.etree.cElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()

for bean in root.findall('Bean'):
for status in bean.findall('Status'):
if 'Adapters' in status.get('name'):
for status2 in status.findall('Status'):
for prop in status2.findall('Prop'):
if 'linesRead' in prop.get('name'):
print prop.text

最佳答案

不确定您希望如何打印最终结果,但您可以使用单个 XPath 表达式一次性完成:

for lines in root.findall('.//Bean/Status[@name="Adapters"]/Status/Prop[@name="linesRead"]'):
print(lines.text)

打印 0 作为示例数据。

关于python - 使用 Python 中的 xml 子对象、ElementTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33312911/

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