Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python etree获取xml的属性_Python_Python 2.7_Xml Parsing_Elementtree_Xml.etree - Fatal编程技术网

使用python etree获取xml的属性

使用python etree获取xml的属性,python,python-2.7,xml-parsing,elementtree,xml.etree,Python,Python 2.7,Xml Parsing,Elementtree,Xml.etree,这是我的xml <Departments orgID="1234 " name="This is Demo Name"> <Department> . . </Department> <Department> . . </Department> </Departments> 我所尝试的 import urllib2 import lxml.etree as ET url="url

这是我的
xml

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


</Departments>
我所尝试的

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
回溯(最近一次呼叫最后一次):
文件“D:\JAVA\test img\test\test.py”,第12行,在
打印root.xpath('//Departments/orgID[text()=“1234”]/前面的同级::name/text()')[0]
索引器:列表索引超出范围

我在这里做错了什么?

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

差不多

root.find("/Departments/orgID").attrib['text']
ect
我使用ET已经一年多了,所以我帮不了你太多:)

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

xpath似乎不匹配,因为当您请求第一个元素时,只有空列表才能得到索引错误
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')