我想解析一个 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: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 文件中
目前我的代码如下所示:
#!/usr/bin/env python
import xml.etree.ElementTree as ET
import csv
tree = ET.parse("file.xml")
root = tree.getroot()
# open csv file for writing
data = open('test.csv', 'w')
# create csv writer object
csvwriter = csv.writer(data)
# filter xml file
for 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 xml
data.close()
最好的祝福
湖上湖
相关分类