gpt4 book ai didi

python - 在Python中解析XML

转载 作者:太空宇宙 更新时间:2023-11-03 18:05:45 25 4
gpt4 key购买 nike

我有一个 XML,我想解析它然后将结果发送到 txt 文件中。

XML 文件是由如下 block 构建的:

<rpc-reply message-id="12"
xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<user-stats>
<allocated-user-count>10</allocated-user-count>
<current-user-count>3</current-user-count>
<max-active-user-count-24hrs>2</max-active-usercount-
24hrs>
<min-active-user-count-24hrs>0</min-active-usercount-
24hrs>
</user-stats>
</rpc-reply>

所有 block 都以 and 开头

我想删除所有标签并按行获取结果并将它们复制到文本文件中。例如:

allocated user count <tab> current-user-count <tab> max-user-count
100 <tab> 1<tab> 2<tab>
100 <tab> 0<tab> 2<tab> (info taken from the second RPC block)

等等

有什么办法可以做到这一点吗?

最佳答案

您可以使用xmltodict用于此的模块。

您需要使用

安装它
pip install xmltodict

一旦你有了它,就去做

import xmltodict
data = xmltodict.parse(xmldata)

这将为您提供一个早期可遍历的 python 字典,然后您可以使用它来获取您想要的值。

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

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