如何在python中搜索XML元素?

2024-06-08 21:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

下面显示的代码运行得很好,但问题是我需要手动设置名称空间,比如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,
    }

Tags: 名称元素datadef空间手动soapdom
1条回答
网友
1楼 · 发布于 2024-06-08 21:50:31

因为您的代码使用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/>

相关问题 更多 >