使用python etree获取xml的属性

时间:2014-03-21 07:46:59

标签: python python-2.7 xml-parsing elementtree xml.etree

这是我的xml

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


</Departments>

我想使用orgID获取此xml的属性。

假设orgID=1234则输出

This is Demo Name

我尝试了什么,

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]

但是得到错误,

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

我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

<Departments>是XML文档的根吗?如果是这样,那么这是否合适?

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

答案 1 :(得分:1)

ET没有完整的xpath支持,您应该使用lxml或使用find,search .attrib和looping写出完整的逻辑:(

类似

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

自从我使用ET已经超过一年了,所以我无法帮助你更多:)