0

私はフォームのxmlを持っています

<root>
  <tag1>   </tag1>
  <tag2>   </tag2>
  <tag3>   </tag3>

  <tag1>   </tag1>
  <tag2>   </tag2>
  <tag3>   </tag3>
</root>

xmlを順番に解析する必要があります

tag1 -> tag2 -> tag3 -> tag1 -> tag2 -> tag3 

現在、私は使用しています

root = tree.getroot()
for data in root.findall('tag1')
    do_operations(data)
for data in root.findall('tag2')
    do_operations(data)

しかし、このアプローチは私に与えており、それは明らかです

tag1 -> tag1 -> tag2 -> tag2 -> tag3 -> tag3

これは私が望むものではありません。

希望する方法で XML をパースできる最適な方法を提案できますか。tag1 、 tag2 、 tag3 は、上記と同じ順序で何度も繰り返されます。

4

2 に答える 2

2

IIUC、単純にroot自分自身をループできませんか?

>>> for data in root:
...     print data
...     
<Element tag1 at 0x102dea7d0>
<Element tag2 at 0x102dea8c0>
<Element tag3 at 0x102dd6d20>
<Element tag1 at 0x102dea7d0>
<Element tag2 at 0x102dea8c0>
<Element tag3 at 0x102dd6d20>
于 2013-03-28T09:44:46.053 に答える
1

find を使用する代わりに、子を反復処理できます。

for child in root:
    do operations...

異なるタグに対して異なる操作を行う場合、child.tag を使用して何を行うかを決定できます。

for child in root:
    if child.tag == 'tag1':
       do operations
    elif child.tag == 'tag2':
       do other operations
    ...

または、操作を dict に入れて、if-elif-else の呪文を避けることもできます。

于 2013-03-28T09:48:35.273 に答える