在python中解析xml文件

时间:2013-12-16 14:09:13

标签: python xml parsing

xml文件:

<global>
    <rtmp>
        <fcsapp>
            <password>
                <key>hello123</key>
                <key>check123</key>
            </password>
        </fcsapp>
    </rtmp>
</global>

python代码:获取所有关键标记值。 hello123 check123

using xml.etree.ElementTree

for streams in xmlRoot.iter('global'):
    xpath = "/rtmp/fcsapp/password"
    tag = "key"
    for child in streams.findall(xpath):
        resultlist.append(child.find(tag).text)

    print resultlist

获得的输出为[hello123],但我希望它同时显示([hello123, check123]

我如何获得这个?

2 个答案:

答案 0 :(得分:2)

使用lxmlcssselect我会这样做:

>>> from lxml.html import fromstring
>>> doc = fromstring(open("foo.xml", "r").read())
>>> doc.cssselect("password key")
[<Element key at 0x7f77a6786cb0>, <Element key at 0x7f77a6786d70>]
>>> [e.text for e in  doc.cssselect("password key")]
['hello123 \n                      ', 'check123 \n                  ']

答案 1 :(得分:0)

使用xml.etree.ElementTree

for streams in xmlRoot.iter('global'):
    xpath = "/rtmp/fcsapp/password"
    tag = "key"
    for child in streams.iter(tag):
        resultlist.append(child.text)

    print resultlist

必须通过for循环中的“key”标记才能获得所需的结果。上面的代码解决了这个问题。