-4

事情是这样的:

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

作为列表。

4

1 回答 1

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]
于 2013-04-11T17:01:25.387 回答