0

i have some data in xml like:

<test a=10 b=20>Hello</test>
<test a=30 b=40>Hi</test>

how do i read value of a, b as well as Hello, and Hi. I have done some thing like:

tt = xml.findall('test')
no  = len(tt)
for i in range (0, no):
    print tt[i].get(a)
    print tt[i].get(b)
    print xml.findtext('test')

this code outputs

10 20 Hello
30 40 Hello

which is wrong for second iteration it should print "Hi" in stead of "Hello".

2 Answers 2

1

You can simply iterate over the return list of xml.findall() rather than using indexes. Something like -

tt = xml.findall('test')
no  = len(tt)
for t in tt:
    print t.get('a')
    print t.get('b')
    print t.text

When you do - xml.findtext() runs the xpath on the complete xml again and gets the text for the first element it finds, that is why you are getting the issue. Just get the .text attribute from the xml element returned by xml.findall() as done above.

Sign up to request clarification or add additional context in comments.

Comments

0

Here Python Doc says about findtext

findtext(match, default=None)
Finds text for the first subelement matching match. match may be a tag name or path. Returns the text content of the first matching element, or default if no element was found. Note that if the matching element has no text content an empty string is returned.

It always find the first subelement matching match hence always Hello.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.