为了账号安全,请及时绑定邮箱和手机立即绑定

当元素包含 smth 时解析 xml 文件。特殊的蟒蛇

当元素包含 smth 时解析 xml 文件。特殊的蟒蛇

德玛西亚99 2021-08-17 16:45:01
我想解析一个 XML 文件并将一些部分写入一个 csv 文件。我会用python来做。我对编程和 XML 很陌生。我读了很多,但我找不到一个有用的例子来解决我的问题。我的 XML 文件如下所示:<Host name="1.1.1.1">   <Properties>      <tag name="id">1</tag>      <tag name="os">windows</tag>      <tag name="ip">1.11.111.1</tag>   </Properties>   <Report id="123">      <output>         Host is configured to get updates from another server.         Update status:            last detected: 2015-12-02 18:48:28            last downloaded: 2015-11-17 12:34:22            last installed: 2015-11-23 01:05:32         Automatic settings:.....       </output>    </Report>    <Report id="123">       <output>          Host is configured to get updates from another server.          Environment Options:          Automatic settings:.....       </output>    </Report></Host>我的 XML 文件包含 500 个这样的条目!我只想解析输出包含Update status 的XML 块,因为我想写入 3 个日期(上次检测、上次下载和上次安装在我的 CSV 文件中。我还将添加 id、os 和 ip。我用 ElementTree 库尝试过,但我无法过滤输出包含更新状态的 element.text。目前我能够从整个文件中提取所有文本和属性,但我无法过滤输出包含更新状态、上次检测到、上次下载或上次安装的块。谁能给一些建议如何实现这一目标?所需的输出:id:1os:windows ip:1.11.111.1 last detected: 2015-12-02 18:48:28last downloaded: 2015-11-17 12:34:22 last installed:2015-11-23 01:05:32 所有这些信息都写在一个 .csv 文件中目前我的代码如下所示:#!/usr/bin/env pythonimport xml.etree.ElementTree as ETimport csvtree = ET.parse("file.xml")root = tree.getroot()# open csv file for writingdata = open('test.csv', 'w')# create csv writer objectcsvwriter = csv.writer(data)# filter xml filefor tag in root.findall(".Host/Properties/tag[@name='ip']"):print(tag.text) # gives all ip's from whole xml for output in root.iter('output'):print(plugin.text) # gives all outputs from whole xmldata.close()最好的祝福
查看完整描述

1 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

当您从<Host>元素开始并按照自己的方式工作时,它相对简单。


迭代所有节点,但只在子字符串"Update status:"出现在 的值中时输出一些东西<output>:


for host in tree.iter("Host"):

    host_id = host.find('./Properties/tag[@name="id"]')

    host_os = host.find('./Properties/tag[@name="os"]')

    host_ip = host.find('./Properties/tag[@name="ip"]')


    for output in host.iter("output"):

        if output.text is not None and "Update status:" in output.text:

            print("id:" + host_id.text)

            print("os:" + host_os.text)

            print("ip:" + host_ip.text)


            for line in output.text.splitlines():

                if ("last detected:" in line or

                    "last downloaded" in line or

                    "last installed"  in line):

                    print(line.strip())

为您的示例 XML 输出此内容:


id:1

os:windows

ip:1.11.111.1

last detected: 2015-12-02 18:48:28

last downloaded: 2015-11-17 12:34:22

last installed: 2015-11-23 01:05:32

次要问题:这不是真正的 CSV,因此将其按原样写入 *.csv 文件不会很干净。


查看完整回答
反对 回复 2021-08-17
  • 1 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号