2011-12-19 2 views
3

私はPythonを使用していますが、XMLをいくつか取り込み、それをdictに変換しようとしています。コードは、奇妙なテキストがdictプロパティ名に追加される要素タグに追加されていることを除いて、正常に動作します。このテキストは、 "WebServiceGeocodeQueryResult"属性の値であると思われます。 "xmlns"。あなたは、デバッガで見ることができるように要素タグ内にxml.etree.ElementTree.xml()がウェブサイト名を含めるのを防ぐ

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

そして、この接頭辞はdictのプロパティ名に変換されます。 enter image description here

答えて

5

「奇妙なテキスト」は要素の名前空間です。 ElementTree expands element names to universal namescElementTreeが利用可能な場合、あなたはそれが速くなるように、その使用する必要があり、余談として

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] 

:あなたはでき

は、このようなあなたの要素名を前処理します。 (import xml.etree.cElementTree as ET