如何在python中搜索XML元素?

时间:2014-04-14 13:48:34

标签: python soap

下面显示的

Сode工作得很好,但问题是我需要手动设置像d:这样的名称空间。是否有可能以某种方式搜索忽略此名称空间的元素,如dom.getElementsByTagName('Scopes')

def parseSoapBody(soap_data):
    dom = parseString(soap_data)

    return {
        'scopes': dom.getElementsByTagName('d:Scopes')[0].firstChild.nodeValue,
        'address': dom.getElementsByTagName('d:XAddrs')[0].firstChild.nodeValue,
    }

1 个答案:

答案 0 :(得分:1)

由于您的代码使用了parseString和getElementsByTagName,我假设您正在使用minidom。在这种情况下,请尝试:

dom.getElementsByTagNameNS('*', 'Scopes')

the docs中没有这样说,但如果您查看xml/dom/minidom.py的源代码,则会看到getElementsByTagNameNS次来电_get_elements_by_tagName_ns_helper其定义如下:

def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
    for node in parent.childNodes:
        if node.nodeType == Node.ELEMENT_NODE:
            if ((localName == "*" or node.localName == localName) and
                (nsURI == "*" or node.namespaceURI == nsURI)):
                rc.append(node)
            _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
    return rc

请注意,当nsURI等于*时,只有localName需要匹配。


例如,

import xml.dom.minidom as minidom
content = '''<root xmlns:f="foo"><f:test/><f:test/></root>'''
dom = minidom.parseString(content)
for n in dom.getElementsByTagNameNS('*', 'test'):
    print(n.toxml())
    # <f:test/>
    # <f:test/>