我想解析一个 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 个这样的条目!我只想解析输出包含更新状态的 XML block ,因为我想在 CSV 文件中写入 3 个日期(上次检测到、上次下载和上次安装)。我还会添加 id,操作系统和IP。
我尝试使用 ElementTree 库,但无法过滤输出包含更新状态的 element.text。目前,我能够从整个文件中提取所有文本和属性,但无法过滤输出包含更新状态、上次检测、上次下载或上次安装的 block 。
任何人都可以提供一些如何实现这一目标的建议吗?
所需输出:
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()
最诚挚的问候
最佳答案
当您从<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 文件并不是很干净。
关于python - 当元素包含某些内容时解析 xml 文件。特别是Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53299429/