【发布时间】:2012-04-19 00:35:43
【问题描述】:
我需要一些关于 python 的帮助。我是python新手。我曾经用 Objective-C 编写过很多程序。
在 Objective-C 中,我能够将 NSDictionary 保存为 xml 文件并使用简单的命令直接加载它。这是我保存的 xml 字典的示例:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>1</key>
<string>Object One</string>
<key>2</key>
<string>Object Two</string>
<key>3</key>
<string>Object Three</string>
</dict>
</plist>
如果我在 Objective-C 中加载它,我可以直接将字典作为 NSDictionary 获取。
所以我的问题是:如何在 Python 中轻松做到这一点。我发现了一些使用解析器(例如 lxml)的东西。我设法加载了数据,但我无法获得只有键和值的字典。 我在互联网上搜索了很多,但找不到合适的东西。 有没有人有想法或建议?
我试过这个:http://code.activestate.com/recipes/410469-xml-as-dictionary/ 但我没能成功。
提前,非常感谢!
【问题讨论】:
-
“我没能成功。”那么,有什么问题呢?
-
我收到这个错误:如果 len(element) == 1 or element[0].tag != element[1].tag: File "lxml.etree.pyx", line 1054, in lxml.etree._Element.__getitem__ (src/lxml/lxml.etree.c:38293) IndexError: list index out of range 我知道这意味着我要去很远的地方但是我没有改变代码除了那个当我运行它时,它说我需要将“if element”更改为“if element is not None”
标签: python objective-c xml parsing dictionary