2013-03-28 61 views
0

我有如下形式的XMLElementTree的解析在python

<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按照上面給出的相同順序重複了很多次。

+0

你在使用什麼模塊/庫? – pradyunsg 2013-03-28 09:46:06

+0

@Schoolboy ElementTree? – 2013-03-28 09:54:57

回答

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> 
+0

什麼是0x102dea7d0? – Abhishek 2013-03-28 09:45:36

+0

@Abhishek:這些僅僅是'id()'結果的十六進制版本,作爲區分具有'__repr__'中相同名稱的標記的一種方式。 – DSM 2013-03-28 09:47:37

+0

如果我讓它們在XML中重複100次會怎樣。我不能用這種方式寫他們 – Abhishek 2013-03-28 09:48:57

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 
    ... 

或者你可以把操作放在一個字典中,並避免if-elif-else咒語。

+0

謝謝,這是整齊。投票了.. – Abhishek 2013-03-28 09:50:39