使用ElementT解析XML

2024-04-16 14:34:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用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>'

美化:

^{pr2}$

我使用这段小代码将字符串转换为可搜索的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>

搜索标签和属性的最简单方法是什么,比如在beauthoulsoup模块中?例如,如何轻松地检索类元素的className和p属性?我一直在读关于lxml的不同的东西,xml.dom.minidom,和ElementTree,但我一定错过了一些东西,因为我似乎得不到我想要的东西。在


Tags: 字符串comapihttp属性xmlelementat
1条回答
网友
1楼 · 发布于 2024-04-16 14:34:51

{{cd2>上面的第一个节点{

>>> tree
<Element '{http://api.uclassify.com/1/ResponseSchema}uclassify' at 0x101f56410>

Find只查看当前节点的子节点,因此tree.find只能找到status和{}标记。在

最后,xml名称空间正在调整所有内容的名称,因此您需要获取xmlns并使用它来构建标记名:

^{pr2}$

例如,要获得3class标记,您需要:

classify = readCalls.find('{%s}classify' % (xmlns,))
classification = classify.find('{%s}classification' %(xmlns,))
classes = classification.findall('{%s}classes'%(xmlns,))

相关问题 更多 >