Domanda

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 ?

È stato utile?

Soluzione

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

Altri suggerimenti

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 :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top