我有一个如下所示的xml:
<root>
<G>
<G1>1</G1>
<G2>some text</G2>
<G3>some text</G3>
<GP>
<GP1>1</GP1>
<GP2>a</GP2>
<GP3>a</GP3>
</GP>
<GP>
<GP1>2</GP1>
<GP2>b</GP2>
<GP3>b</GP3>
</GP>
<GP>
<GP1>3</GP1>
<GP2>c</GP2>
<GP3>c</GP3>
</GP>
</G>
<G>
<G1>2</G1>
<G2>some text</G2>
<G3>some text</G3>
<GP>
<GP1>1</GP1>
<GP2>aa</GP2>
<GP3>aa</GP3>
</GP>
<GP>
<GP1>2</GP1>
<GP2>bb</GP2>
<GP3>bb</GP3>
</GP>
<GP>
<GP1>3</GP1>
<GP2>cc</GP2>
<GP3>cc</GP3>
</GP>
</G>
<G>
<G1>3</G1>
<G2>some text</G2>
<G3>some text</G3>
<GP>
<GP1>1</GP1>
<GP2>aaa</GP2>
<GP3>aaa</GP3>
</GP>
<GP>
<GP1>2</GP1>
<GP2>bbb</GP2>
<GP3>bbb</GP3>
</GP>
<GP>
<GP1>3</GP1>
<GP2>ccc</GP2>
<GP3>ccc</GP3>
</GP>
</G>
</root>
我正试图将这个xml转换成一个名为“G”的嵌套字典:
^{pr2}$我的代码可以很好地得到所有在“G”下的元素,例如G1、G2等等,但是对于GP,我要么只得到一条记录,要么我得到所有的它们,但是它重复了几次,要么我在字典中的一个GP下得到了所有9个GP元素。这是我的代码:
f = 'path to file'
tree = ET.parse(f)
root = tree.getroot()
self.tree = tree
self.root = root
gs = len(self.tree.getiterator('G'))
g = {}
for i in range(0, gs):
d = {}
for elem in self.tree.getiterator('G')[i]:
if elem.text == "\n " and elem.tag not in ['GP']:
dd = {}
for parent in elem:
if parent.text == "\n ":
ddd = {}
for child in parent:
ddd[child.tag] = child.text
dd[parent.tag] = ddd
else:
dd[parent.tag] = parent.text
d[elem.tag] = dd
else:
d[elem.tag] = elem.text
g[i+1] = d
# Build GP
count = 0
gp = {}
for elem in self.tree.getiterator('GP'):
d = {}
for parent in elem:
if parent.text == "\n ":
dd = {}
for child in parent:
dd[child.tag] = child.text
d[parent.tag] = dd
else:
d[parent.tag] = parent.text
count += 1
gp[count] = d
g["GP"] = gp
代码.py:
注意事项:
输出:
相关问题 更多 >
编程相关推荐