我将标准输出放在下面的表单中,需要为下面的输出生成xml>; 如何在python中生成xml。 循环中的子元素读取标准输出。但它不能生成正确的xml。它正在生成只有一个子元素的xml。你知道吗
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
我需要以下格式的xml
<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 = 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")
comment = ET.SubElement(machine, "comment")
for line in lines.split("\n"):
if 'MAC' in line:
mac = line.split(":")
stnmac.text = str(mac[1].strip())
if 'IP' in line:
ip = line.split(":")
stnip.text = str(ip[1].strip())
if 'NAME' in line:
name = line.split(":")
apidname.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 'Comment' in line:
user = line.split(":")
userexp.text = str(user[1].strip())
tree = ET.ElementTree(results)
tree.write('machine.xml')
相同的属性在xml中重复,如果我在循环中放入子元素,那么每台机器在xml中只有一个属性。你知道吗
下面是一个使用
xml.etree.ElementTree
的解决方案:它打印:
您可以使用BeautifulSoup。其思想是将字符串拆分为新行(或逐行读取源文件),并在每一空行上创建
machine
标记。在每个非空行上,按第一个:
拆分行,创建一个标记并附加到machine
标记。你知道吗下面是一个您可以开始使用的工作示例:
印刷品:
附言:我真的不喜欢“分组”的部分-看起来不像Python,但工作。你知道吗
希望有帮助。你知道吗
相关问题 更多 >
编程相关推荐