python - 防止 xml.etree.ElementTree.xml( ) 在元素标签中包含网站名称

标签 python xml

我正在使用 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/ }”: enter image description here

这个前缀被翻译成字典属性名称: enter image description here

最佳答案

那个“奇怪的文本”是元素的 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/

相关文章:

python - 如果 df1 索引在 df2 索引中,Pandas 更新列值

html - 如何使用 nginx 在 XSL 转换样式表上获取 "text/plain"输出?

python - 如何反转输出的顺序

android - 如何在Android中写一个类似于Python函数的hash函数?

java - 异常处理指南——Python 与 Java

java - haarcascade_frontalface_alt.xml 不工作

java - 如何在 mainActivity 布局的工具栏中删除这个箭头?

javascript - 代理阻止 websockets?如何绕行

java - 使用bean引用从spring xml配置迁移到@Configuration(servlet 3.0)会导致BeanNotOfRequiredTypeException

android - 未找到 MotionLayout 类或未找到属性 layoutDescription