2010-10-04 51 views

回答

0

下面的食譜應該是有幫助的:

+0

,這不是一個很好的答案;除了它只是鏈接到一個庫,它沒有提供如何在答案中使用它的例子;沒有鏈接,這個答案變得毫無用處。 – 2015-04-07 01:51:22

-2

我認爲最好的辦法是自己推出適合你的需求。獲取lxml,閱讀文檔,你應該很好去。如果你有疑問,馬上回來:)

1

當在XML和Python字典之間轉換時,有一些有趣的角落案例使得這些不平凡(屬性?列表?匿名列表?單個條目列表?內容評估? ): 故事一起來看看從PicklingTools發行本文件:XML to Dict conversionshttp://www.picklingtools.com

該文檔討論如何做到這一點,但這裏有一個簡單的例子。 在一個名爲「的example.xml」文件,我們將會把下面的XML:

<top> 
    <a>1</a> 
    <b>2.2</b> 
    <c>three</c> 
</top> 

爲了處理這個文件,並把它變成一本字典:

>>> from xmlloader import * 
>>> example = file('example.xml', 'r') 
>>> xl = StreamXMLLoader(example, 0) # 0 = All defaults on options 
>>> result = xl.expectXML() 
>>> print result 
{'top': {'a': '1', 'c': 'three', 'b': '2.2'}} 
10

xmltodict(全面披露:我寫的它)確實如此,繼此"standard"。它基於Expat,所以速度非常快,不需要在內存中加載整個XML樹。

>>> print(json.dumps(xmltodict.parse(""" 
... <mydocument has="an attribute"> 
... <and> 
...  <many>elements</many> 
...  <many>more elements</many> 
... </and> 
... <plus a="complex"> 
...  element as well 
... </plus> 
... </mydocument> 
... """), indent=4)) 
{ 
    "mydocument": { 
     "@has": "an attribute", 
     "and": { 
      "many": [ 
       "elements", 
       "more elements" 
      ] 
     }, 
     "plus": { 
      "@a": "complex", 
      "#text": "element as well" 
     } 
    } 
} 
+0

就目前來看,這不是一個很好的答案;除了它只是鏈接到一個庫,它沒有提供如何在答案中使用它的例子;沒有鏈接,這個答案變得毫無用處。 – 2015-04-07 01:50:58

+0

Martin,您能否提供一個xmltodict使用流示例?一個簡單的工作例子會很棒。我有很大的XML文件不適合內存,所以流式處理的例子會很棒。文檔中的一個很難理解。 – ThinkCode 2016-02-04 20:53:21

0

我可能會建議考慮看看declxml,看它是否符合你的使用情況(全面披露:我是作者)。使用declxml,您可以創建名爲的處理器,它聲明式地定義XML文檔的結構。處理器用於解析和序列化XML和Python值,包括對象,字典和namedtuples。

import declxml as xml 

some_xml = """ 
<mydocument has="an attribute"> 
    <and> 
    <many>elements</many> 
    <many>more elements</many> 
    </and> 
    <plus a="complex"> 
    element as well 
    </plus> 
</mydocument> 
""" 

processor = xml.dictionary('mydocument', [ 
    xml.string('.', attribute='has'), 
    xml.array(xml.string('many'), nested='and'), 
    xml.dictionary('plus', [ 
     xml.string('.', attribute='a'), 
     xml.string('.', alias='plus') 
    ]) 
]) 

xml.parse_from_string(processor, some_xml) 

因爲它的立場將會產生以下輸出

{'has': 'an attribute', 
'and': ['elements', 'more elements'], 
'plus': {'a': 'complex', 'plus': 'element as well'}}