我需要解析XML文件并为其创建一个等效的Dictionary。
我已经完成了之前的Stack Overflow问题。
Converting xml to dictionary using ElementTree
现在我有一个XML内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<Data>
<Person>
<First>John</First>
<Last>Smith</Last>
<extra>
<details1>
<married>yes</married>
<status>rich</status>
</details1>
</extra>
</Person>
<Person>
<First>Jane</First>
<Last>Doe</Last>
<extra>
<details1>
<married>yes</married>
<status>rich</status>
</details1>
<details2>
<property>yes</property>
</details2>
</extra>
</Person>
</Data>
它返回输出如下:
[
{
"extra": "\n\t\t",
"Last": "Smith",
"First": "John"
}
]
[
{
"extra": "\n\t\t",
"Last": "Smith",
"First": "John"
},
{
"extra": "\n\t\t",
"Last": "Doe",
"First": "Jane"
}
]
所以我需要一种方法来解析子元素的内容并返回结果,请让我知道相同的方法。
当前代码:
import json
from lxml import etree
tree= etree.parse("dummy.xml")
root = tree.getroot()
datadict = []
for item in root:
d = {}
for elem in item:
d[elem.tag]=elem.text
datadict.append(d)
new_d = json.dumps(datadict, indent=1)
print new_d