gpt4 book ai didi

python - 在 python 中以正确格式输出 XML

转载 作者:太空宇宙 更新时间:2023-11-04 04:01:44 24 4
gpt4 key购买 nike

代码是:

results = ET.Element("results")
machine = ET.SubElement(results,"machine")
mac = ET.SubElement(machine, "mac")
ip = ET.SubElement(machine,"ip")
name = ET.SubElement(machine,"name")
download = ET.SubElement(machine, "download")
upload = ET.SubElement(machine, "upload")
comments = ET.SubElement(machine, "comments")

for line in lines.split("\n"):
if 'MAC' in line:
mac = line.split(":")
mac.text = str(mac[1].strip())
if 'IP' in line:
ip = line.split(":")
ip.text = str(ip[1].strip())
if 'NAME' in line:
name = line.split(":")
name.text = str(name[1].strip())
if 'Download' in line:
down = line.split(":")
download.text = str(down[1].strip())
if 'Upload' in line:
up = line.split(":")
upload.text = str(up[1].strip())
if 'Comments' in line:
user = line.split(":")
comments.text = str(user[1].strip())

tree = ET.ElementTree(results)
tree.write('machine.xml')

需要转换为 xml 的实际 stdout 输出是

MAC             : 00:19:ec;dc;bc
IP : 192.111.111.111
NAME : 900, Charles
Download : 36MB
Upload : 12MB
comments : Since total througput is very less, we cannot continue

MAC : 00:19:ac:bc:cd:
IP : 192.222.222.222
NAME : 800, Babbage
Download : 36MB
Upload : 24MB
comments : Since total througput is high, we can continue

我需要生成的实际格式是

<results>
<machine>
<MAC>00:19:ec;dc;bc</MAC>
<ip>192.111.111.111</ip>
<name>900, Charles</name>
<upload>36MB</upload>
<download>12MB</download>
<comments>Since total througput is very less, we cannot continue</comments>
</machine>
<machine>
<MAC>00:19:ac:bc:cd:</MAC>
<ip>192.222.222.222</ip>
<name>800, Babbage</name>
<upload>36MB</upload>
<download>24MB</download>
<comments>Since total througput is high, we can continue</comments>
</machine>
</results>

我得到的输出是

<results>
<machine>
<MAC>00:19:ec;dc;bc</MAC>
<ip>192.111.111.111</ip>
<name>900, Charles</name>
<upload>36MB</upload>
<download>12MB</download>
<comments>Since total througput is very less, we cannot continue</comments>
</machine>
<machine>
<MAC>00:19:ec;dc;bc</MAC>
<ip>192.111.111.111</ip>
<name>900, Charles</name>
<upload>36MB</upload>
<download>12MB</download>
<comments>Since total througput is very less, we cannot continue</comments>
</machine>
</results>

我使用的是python 2.4(它很旧,但目前无法升级)。如果有人能提出错误是什么,那就太好了。

谢谢!

最佳答案

您只需创建一次子元素,并在每次运行循环时更改其内容。

每次开始读取新机器时,都会在循环内创建子级。也许在循环外有一个哨兵,并在遇到空行时重置它。

关于python - 在 python 中以正确格式输出 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22725929/

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