我想找到一些很好的解決方案,以XML與dict,反之亦然轉換在python如何將XML轉換爲詞典
回答
下面的食譜應該是有幫助的:
我認爲最好的辦法是自己推出適合你的需求。獲取lxml,閱讀文檔,你應該很好去。如果你有疑問,馬上回來:)
當在XML和Python字典之間轉換時,有一些有趣的角落案例使得這些不平凡(屬性?列表?匿名列表?單個條目列表?內容評估? ): 故事一起來看看從PicklingTools發行本文件:XML to Dict conversions:http://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'}}
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"
}
}
}
就目前來看,這不是一個很好的答案;除了它只是鏈接到一個庫,它沒有提供如何在答案中使用它的例子;沒有鏈接,這個答案變得毫無用處。 – 2015-04-07 01:50:58
Martin,您能否提供一個xmltodict使用流示例?一個簡單的工作例子會很棒。我有很大的XML文件不適合內存,所以流式處理的例子會很棒。文檔中的一個很難理解。 – ThinkCode 2016-02-04 20:53:21
我可能會建議考慮看看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'}}
- 1. 如何XML轉換爲詞典
- 2. 如何將XML轉換爲詞典字典
- 3. 如何將JSON字典轉換爲XML?
- 4. 試圖XML轉換爲詞典
- 5. 將字典轉換爲XML
- 6. 如何將詞典字典轉換爲Ansible vars文件中的詞典列表?
- 7. 將詞典列表轉換爲嵌套詞典
- 8. 將XML文件轉換爲多維詞典
- 9. 將XML轉換爲VB.NET字典
- 10. 將XML文檔轉換爲字典
- 11. 將XML文檔轉換爲字典
- 12. 將單詞2007文件轉換爲XML
- 13. 如何將3級詞典轉換爲所需的格式?
- 14. 轉換詞典的詞典串
- 15. 如何將SVG xml轉換爲BPMN2.0 xml
- 16. 將列表列表轉換爲字典詞典(Python)
- 17. 如何將字典多級轉換爲xml?
- 18. 如何使用表達式將XML轉換爲字典?
- 19. 如何將單個單詞轉換爲有效的xml?
- 20. 轉換如何HttpResponse對象到詞典
- 21. 將數據轉換成詞典的詞典在Python
- 22. 如何將字典轉換爲數組
- 23. 如何將ConcurrentDictionary轉換爲字典?
- 24. 如何將NSDictionary轉換爲Python字典?
- 25. 如何將此unicode轉換爲字典?
- 26. 如何將元組轉換爲字典?
- 27. 如何將列表轉換爲字典?
- 28. 如何將字典轉換爲ConcurrentDictionary?
- 29. 如何將1 - 1000轉換爲單詞?
- 30. 如何將單詞轉換爲鏈接?
,這不是一個很好的答案;除了它只是鏈接到一個庫,它沒有提供如何在答案中使用它的例子;沒有鏈接,這個答案變得毫無用處。 – 2015-04-07 01:51:22