简体   繁体   中英

Get Attribute of xml using python etree

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 ?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM