【问题标题】:python minidom read xmlpython minidom读取xml
【发布时间】:2017-07-19 06:32:10
【问题描述】:

我有这个 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)

这会将空字符串返回给我。有什么帮助吗?

【问题讨论】:

  • startDateTimegeneral 的子元素,而不是属性。
  • @mzjn 你是对的。谢谢
  • 我写道:general=doc.getElementsByTagName('startDateTime')[0].firstChild.data

标签: python xml minidom


【解决方案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

【讨论】:

  • 感谢@Mike Robins,但我想使用 minidom,因为我将它用于 xml 的其他部分。
  • 不客气。如果您曾经在 HTML 上苦苦挣扎,Beautiful Soup 包非常好并且被广泛使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-14
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 2012-11-15
相关资源
最近更新 更多