python中的xml文件解析

python中的xml文件解析,python,xml,parsing,lxml,xpath,Python,Xml,Parsing,Lxml,Xpath,xml文件: <global> <rtmp> <fcsapp> <password> <key>hello123</key> <key>check123</key> </password> </fcsapp> </

xml文件:

<global>
    <rtmp>
        <fcsapp>
            <password>
                <key>hello123</key>
                <key>check123</key>
            </password>
        </fcsapp>
    </rtmp>
</global>
获得的输出是[hello123],但我希望它同时显示[hello123,check123]

如何获得此信息?

使用,我会这样做:

>>> 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                  ']
使用,我会这样做:

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

尝试使用beautifulsoup软件包

尝试使用beautifulsoup软件包

,您可以通过以下方式执行此操作:

from lxml import etree

xml = """
<global>
    <rtmp>
        <fcsapp>
            <password>
                <key>hello123</key>
                <key>check123</key>
            </password>
        </fcsapp>
    </rtmp>
</global>
"""

tree = etree.fromstring(xml)
result = tree.xpath('//password/key/text()')
print result #  ['hello123', 'check123']
使用和,您可以通过以下方式执行此操作:

from lxml import etree

xml = """
<global>
    <rtmp>
        <fcsapp>
            <password>
                <key>hello123</key>
                <key>check123</key>
            </password>
        </fcsapp>
    </rtmp>
</global>
"""

tree = etree.fromstring(xml)
result = tree.xpath('//password/key/text()')
print result #  ['hello123', 'check123']

使用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循环中的键标记进行迭代,以获得所需的结果。上面的代码解决了这个问题。

使用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循环中的键标记进行迭代,以获得所需的结果。上面的代码解决了这个问题。

使用代码格式化{}按钮,而不是引用。。。那么你就不必破坏你的XML了。使用代码格式化{}按钮,不要引用。。。这样,您就不必破坏XML。在那里标记的用法很好:在那里标记的用法很好: