dreamer
dreamer

Reputation: 478

xml file parsing in python

xml file :

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

python code : To obtain all the key tag values. 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

The output obtained is [hello123], but I want it to display both ([hello123, check123])

How do I obtain this?

Upvotes: 2

Views: 146

Answers (4)

dreamer
dreamer

Reputation: 478

using 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

have to iter over the "key" tag in for loop to obtain the desired result. The above code solves the problem.

Upvotes: 0

Alexander Zhukov
Alexander Zhukov

Reputation: 4547

With and You can do it in the following way:

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

Upvotes: 2

Palash Kumar
Palash Kumar

Reputation: 429

try beautifulsoup package "https://pypi.python.org/pypi/BeautifulSoup"

Upvotes: 0

James Mills
James Mills

Reputation: 19030

Using lxml and cssselect I would do it like this:

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

Upvotes: 2

Related Questions