minidom.parse阅读简短的XML?

时间:2014-02-04 11:11:09

标签: python xml xml-parsing minidom

以下是两个类似的XML文件:

长XML

<mynode>
   <text>Blah</text>
   <position>322,13</position>
</mynode>

短XML

<mynode text="Blah" position="322,13" />

似乎Python的minidom.parse不喜欢短XML

短XML样式是否可用minidom(XML)?

是否可以编写一个既读取短XML又读取长XML的唯一代码?

2 个答案:

答案 0 :(得分:2)

from xml.dom import minidom

def getChild(n,v):
    for child in n.childNodes:
        if child.localName==v:
            yield child

def getValue(n, val):
    res = None
    for n in mynode:
        rv = getChild(n,val)
        for v in rv:
            var = v.childNodes[0].nodeValue
            res = var
    if not res:
        for n in mynode:
            attr = n.getAttributeNode(val)
            if attr:
                res = attr.nodeValue.strip()

    return res


xmldoc = minidom.parse('file.xml')
mynode = xmldoc.getElementsByTagName('mynode')
print getValue(mynode,'text')
print getValue(mynode,'position')

输出:

Blah
322,13

答案 1 :(得分:1)

您需要一个根节点

>>> from xml.dom.minidom import parseString
>>> doc = parseString('<root><mynode text="Blah" position="322,13" /></root>')
>>> print d.firstChild.firstChild.getAttribute('text')
Blah
>>> print d.firstChild.firstChild.getAttribute('position')
322,13