2014-04-14 80 views
0

下面显示的Сode工作正常,但问题是我需要手动设置名称空间,如d:。是否有可能以某种方式搜索忽略此名称的元素,如dom.getElementsByTagName('Scopes')如何搜索python中的XML元素?

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

由于你的代码使用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/>