2

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?

1
  • Use code formatting (the {} button), not quoting... (Then you don't have to mangle your XML). Commented Dec 16, 2013 at 14:11

4 Answers 4

2

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                  ']
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Nice use of tagging there :)
0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.