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]
的名单。
答
只需拆分属性值并将它们转换为每个元素的整数。
随着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]
答
这是认为这两个问题的解析容易得多。首先,XML解析位为您提供属性1和属性2的字符串值。
有了这些值之后,您只是想将逗号分隔列表解析为数组,这是另一个与XML无关的解析问题。
欢迎来到Stack Overflow!看起来你希望我们为你写一些代码。尽管许多用户愿意为遇险的编码人员编写代码,但他们通常只在海报已尝试自行解决问题时才提供帮助。证明这一努力的一个好方法是包含迄今为止编写的代码,示例输入(如果有的话),期望的输出和实际获得的输出(控制台输出,堆栈跟踪,编译器错误 - 无论是适用)。您提供的细节越多,您可能会收到的答案就越多。 – 2013-04-11 16:58:55