2013-04-11 45 views
-4

事情是這樣的:Python。解析XML:屬性越來越分隔值的列表

<parent> 
    <child attribute1="100" attribute2="1,2"/> 
    <child attribute1="200" attribute2="1,2,5"/> 
    <child attribute1="300" attribute2="1,2,5,10"/> 
</parent> 

想我分析之後看到:

100 [1, 2] 
200 [1, 2, 5] 
300 [1, 2, 5, 10] 

的名單。

+5

歡迎來到Stack Overflow!看起來你希望我們爲你寫一些代碼。儘管許多用戶願意爲遇險的編碼人員編寫代碼,但他們通常只在海報已嘗試自行解決問題時才提供幫助。證明這一努力的一個好方法是包含迄今爲止編寫的代碼,示例輸入(如果有的話),期望的輸出和實際獲得的輸出(控制檯輸出,堆棧跟蹤,編譯器錯誤 - 無論是適用)。您提供的細節越多,您可能會收到的答案就越多。 – 2013-04-11 16:58:55

回答

0

只需拆分屬性值並將它們轉換爲每個元素的整數。

隨着ElementTree

from xml.etree import ElementTree 

tree = ElementTree.fromstring(example) 

for child in tree.findall('.//child'): 
    attribute1 = int(child.attrib['attribute1']) 
    attribute2 = [int(v) for v in child.attrib['attribute2'].split(',')] 
    print attribute1, attribute2 

對於示例文件,這個打印出:

>>> for child in tree.findall('.//child'): 
...  attribute1 = int(child.attrib['attribute1']) 
...  attribute2 = [int(v) for v in child.attrib['attribute2'].split(',')] 
...  print attribute1, attribute2 
... 
100 [1, 2] 
200 [1, 2, 5] 
300 [1, 2, 5, 10] 
+0

'find_all'應該是'findall' :) – LotusH 2013-04-11 17:10:10

+0

啊!好的。讓它工作。只是'.parse'而不是'fromstring'。非常感謝你。 – meenauh 2013-04-11 17:19:10

+0

@meenauh:我在這裏使用了'fromstring',因爲我在Python字符串中有你的示例文本,但'.parse()'確實是你需要的一個文件。 – 2013-04-11 17:20:57

0

這是認爲這兩個問題的解析容易得多。首先,XML解析位爲您提供屬性1和屬性2的字符串值。

有了這些值之後,您只是想將逗號分隔列表解析爲數組,這是另一個與XML無關的解析問題。