使用ElementTree解析XML
问题描述:
我正在尝试使用ElementTree在XML字符串中搜索标签和属性。这里是字符串:使用ElementTree解析XML
'<?xml version="1.0" encoding="UTF-8" ?>\n<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.01">\n\t<status success="true" statusCode="2000"/>\n\t<readCalls>\n\t<classify id="thing">\n\t\t<classification textCoverage="0">\n\t\t\t<class className="Astronomy" p="0.333333"/>\n\t\t\t<class className="Biology" p="0.333333"/>\n\t\t\t<class className="Mathematics" p="0.333333"/>\n\t\t</classification>\n\t</classify>\n\t</readCalls>\n</uclassify>'
美化:
<?xml version="1.0" encoding="UTF-8" ?>
<uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.01">
<status success="true" statusCode="2000"/>
<readCalls>
<classify id="thing">
<classification textCoverage="0">
<class className="Astronomy" p="0.333333"/>
<class className="Biology" p="0.333333"/>
<class className="Mathematics" p="0.333333"/>
</classification>
</classify>
</readCalls>
</uclassify>
我用这个小码打开字符串转换成可搜索的XML树:
>>> from xml.etree.ElementTree import fromstring, ElementTree
>>> tree = ElementTree(fromstring(a))
我想到用tree.find('uclassify')
将返回该元素/标签,但它似乎什么都不返回。我也试过:
for i in tree.iter():
print i
它打印的东西,但不是我想要的:
<Element '{http://api.uclassify.com/1/ResponseSchema}uclassify' at 0x1011ec410>
<Element '{http://api.uclassify.com/1/ResponseSchema}status' at 0x1011ec390>
<Element '{http://api.uclassify.com/1/ResponseSchema}readCalls' at 0x1011ec450>
<Element '{http://api.uclassify.com/1/ResponseSchema}classify' at 0x1011ec490>
<Element '{http://api.uclassify.com/1/ResponseSchema}classification' at 0x1011ec4d0>
<Element '{http://api.uclassify.com/1/ResponseSchema}class' at 0x1011ec510>
<Element '{http://api.uclassify.com/1/ResponseSchema}class' at 0x1011ec550>
<Element '{http://api.uclassify.com/1/ResponseSchema}class' at 0x1011ec590>
什么是搜索标签和属性,如BeautifulSoup模块中的最简单的方法?例如,我怎样才能轻松地检索类元素的className和p属性?我一直在阅读关于lxml,xml.dom.minidom和ElementTree的不同的东西,但是我一定错过了一些东西,因为我似乎无法得到我想要的东西。
答
所有uclassify
首先是根节点,所以如果你只是打印tree
上方你会看到:
>>> tree
<Element '{http://api.uclassify.com/1/ResponseSchema}uclassify' at 0x101f56410>
查找仅着眼于当前节点的孩子,所以tree.find
只能找到status
和readCalls
标签。
最后,XML命名空间调整一切的名字,所以你需要抓住的xmlns并用它来建立自己的标签名称:
xmlns = tree.tag.split("}")[0][1:]
readCalls = tree.find('{%s}readCalls' % (xmlns,))
例如获得3个class
标签,你会需要:
classify = readCalls.find('{%s}classify' % (xmlns,))
classification = classify.find('{%s}classification' %(xmlns,))
classes = classification.findall('{%s}classes'%(xmlns,))