2017-07-19 118 views
0

我有這樣的XML:蟒蛇minidom命名讀取XML

<?DOMParser ?> 
<logbook:LogBook xmlns:logbook="http://www/logbook/1.0" version="1.2"> 
<visits> 
<visit> 
    <general> 
     <startDateTime>2014-01-10T12:22:39.166</startDateTime> 
     <endDateTime>2014-03-11T13:51:31.480</endDateTime> 
    </general> 
</visit> 
<visit> 
<general> 
    <startDateTime>2013-01-10T12:22:39.166</startDateTime> 
    <endDateTime>2013-03-11T13:51:31.480</endDateTime> 
</general> 
</visit> 
</visits> 
</logbook:LogBook> 

我想有從XML輸出:

startDateTime   | endDateTime   | 
-----------------------|-----------------------| 
2014-01-10T12:22:39.166|2014-03-11T13:51:31.480| 
-----------------------|-----------------------| 
2013-01-10T12:22:39.166|2013-03-11T13:51:31.480| 

我使用minidom,所以我寫了:

import xml.dom.minidom as minidom 
doc=minidom.parse('test.xml') 
general=doc.getElementsByTagName('general')[0] 
startDateTime=general.getAttribute('startDateTime') 
print(startDateTime) 

這將返回空字符串給我。這裏有什麼幫助?

+1

'startDateTime'是'general',不是一個屬性的子元素。 – mzjn

+0

@mzjn你是對的。謝謝 – Safariba

+0

我寫道:一般= doc.getElementsByTagName('startDateTime')[0] .firstChild.data – Safariba

回答

1

我更喜歡使用ElementTree類:

from StringIO import StringIO 
from xml.etree.ElementTree import ElementTree 

et = ElementTree(None, StringIO("""<?DOMParser ?> 
<logbook:LogBook xmlns:logbook="http://www/logbook/1.0" version="1.2"> 
<visits> 
    <visit> 
    <general> 
     <startDateTime>2014-01-10T12:22:39.166</startDateTime> 
     <endDateTime>2014-03-11T13:51:31.480</endDateTime> 
    </general> 
    </visit> 
<visit> 
<general> 
    <startDateTime>2013-01-10T12:22:39.166</startDateTime> 
    <endDateTime>2013-03-11T13:51:31.480</endDateTime> 
</general> 
</visit> 
</visits> 
</logbook:LogBook>""")) 

for general in et.iterfind('visits/visit/general'): 
    start = general.findtext('startDateTime') 
    finish = general.findtext('endDateTime') 
    print start, finish 

輸出:

2014-01-10T12:22:39.166 2014-03-11T13:51:31.480 
2013-01-10T12:22:39.166 2013-03-11T13:51:31.480 
+0

感謝@邁克羅賓斯,但我想使用minidom,因爲我用它的xml的其他部分。 – Safariba

+1

不客氣。如果你一直在用[美麗的湯](https://www.crummy.com/software/BeautifulSoup)封裝HTML,那麼它非常好用並被廣泛使用。 –