1

Here is my xml

<Departments orgID="1234 " name="This is Demo Name">
  <Department>
   .
   .
  </Department>
  <Department>
   .
   .
  </Department>


</Departments>

I want to get attribute of this xml using orgID.

Suppose orgID=1234 then output should be

This is Demo Name

What i have tried ,

import urllib2
import lxml.etree as ET
url="url goes here"
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)
print root.xpath('//Departments/orgID[text()="1234"]/preceding-sibling::name/text()')[0]

But getting error ,

Traceback (most recent call last):
  File "D:\JAVA\test-img\test\test.py", line 12, in <module>
    print root.xpath('//Departments/orgID[text()="1234"]/preceding-sibling::name/text()')[0]
IndexError: list index out of range

Whats wrong i am doing here ?

1
  • it seems that your xpath matches nothing, because only a empty list can get an index error when you ask for the first element Commented Mar 21, 2014 at 8:07

2 Answers 2

2

Is <Departments> the root of the XML document? If so, then would this be appropriate?

import urllib2
import lxml.etree as ET
url="url goes here"
xmldata = urllib2.urlopen(url).read()
root = ET.fromstring(xmldata)

if root.get('orgID') == "1234":
  print root.get('name')
Sign up to request clarification or add additional context in comments.

Comments

1

ET doesn't have full xpath support, you should either use lxml or write out the full logic using find, search .attrib, and looping :(

something like

root.find("/Departments/orgID").attrib['text']
ect

it has been more than a year since I used ET so I cannot help you much more :)

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.