gpt4 book ai didi

python - 使用 ElementTree 解析 XML

转载 作者:太空宇宙 更新时间:2023-11-03 19:14:19 25 4
gpt4 key购买 nike

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

Find 仅查看当前节点子节点,因此 tree.find 只能查找 statusreadCalls 标记。

最后,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,))

关于python - 使用 ElementTree 解析 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11876176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com