Python。解析XML:属性越来越分隔值的列表

问题描述:

事情是这样的: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

只需拆分属性值并将它们转换为每个元素的整数。

随着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

这是认为这两个问题的解析容易得多。首先,XML解析位为您提供属性1和属性2的字符串值。

有了这些值之后,您只是想将逗号分隔列表解析为数组,这是另一个与XML无关的解析问题。