我有一个Test.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<SetupConf>
<LocSetup>
<Src>
<Dir1>C:\User1\test1</Dir1>
<Dir2>C:\User2\log</Dir2>
<Dir3>D:\Users\Checkup</Dir3>
<Dir4>D:\Work1</Dir4>
<Dir5>E:\job1</Dir5>
</Src>
</LocSetup>
</SetupConf>
其中节点取决于用户输入。在&#34; Dir&#34;节点可能是1,2,5,10 dir结构定义。根据要求,我可以使用以下Python代码在@Padraic Cunningham的帮助下从Test.xml中提取数据:
from xml.dom import minidom
from StringIO import StringIO
dom = minidom.parse('Test.xml')
Src = dom.getElementsByTagName('Src')
output = ", ".join([a.childNodes[0].nodeValue for node in Src for a in node.getElementsByTagName('Dir')])
print [output]
获得输出:
C:\User1\test1, C:\User2\log, D:\Users\Checkup, D:\Work1, E:\job1
但预期的输出是:
['C:\\User1\\test1', 'C:\\User2\\log', 'D:\\Users\\Checkup', 'D:\\Work1', 'E:\\job1']
答案 0 :(得分:0)
好吧,我自己解决了:
from xml.dom import minidom
DOMTree = minidom.parse('Test0001.xml')
dom = DOMTree.documentElement
Src = dom.getElementsByTagName('Src')
for node in Src:
output = [a.childNodes[0].nodeValue for a in node.getElementsByTagName('Dir')]
print output
获得输出: [u'C:\ User1 \ test1',u'C:\ User2 \ log',u'D:\ Users \ Checkup',u'D:\ Work1',u'E:\ job1']
我相信还有更简单的方法..请让我知道..谢谢你。