我正在使用 python 并尝试获取一些 XML 并将其转换为字典。代码工作正常,除了一些奇怪的文本被添加到元素标签,然后被添加到 dict 属性名称。此文本似乎是“WebServiceGeocodeQueryResult”属性的值:“xmlns”。
我的代码看起来像这样:
import xml.etree.ElementTree as ET
import xml_to_dictionary # This is some code I found, it seems to work fine:
# http://code.activestate.com/recipes/410469-xml-as-dictionary/
def doSomeStuff()
theXML = """
<?xml version="1.0" encoding="utf-8"?>
<WebServiceGeocodeQueryResult
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="https://webgis.usc.edu/">
<TransactionId>7307e84c-d0c8-4aa8-9b83-8ab4515db9cb</TransactionId>
<Latitude>38.8092475915888</Latitude>
<Longitude>-77.2378689948621</Longitude>
...
"""
tree = ET.XML(result.content) # this is where the element names get the added '{https://webgis.usc.edu/}'
xmldict = xml_to_dictionary.XmlDictConfig(tree)
正如您在调试器中看到的那样,对象“树”中的元素名称具有烦人的前缀:“{ https://webgis.usc.edu/ }”:
这个前缀被翻译成字典属性名称:
最佳答案
那个“奇怪的文本”是元素的 namespace 。元素树 expands element names to universal names .
您可以像这样预处理您的元素名称:
tree = ET.XML(thexml)
et = ET.ElementTree(tree) # this is to include root node
for elem in et.getiterator(): #in python 2.7 or greater, getiterator() is unnecessary
elem.tag = elem.tag.split('}', 1)[-1]
顺便说一句,如果 cElementTree
可用,您应该使用它,因为它会更快。 (将 xml.etree.cElementTree 导入为 ET
)
关于python - 防止 xml.etree.ElementTree.xml( ) 在元素标签中包含网站名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8556501/