【问题标题】:Parsing XML with ElementTree使用 ElementTree 解析 XML
【发布时间】:2012-08-09 03:00:16
【问题描述】:

我正在尝试使用 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 的不同内容,但我一定遗漏了一些东西,因为我似乎无法得到我想要的东西。

【问题讨论】:

    标签: python xml parsing lxml elementtree


    【解决方案1】:

    首先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,))
    

    【讨论】:

      猜你喜欢
      • 2021-02-06
      • 2017-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2014-02-06
      • 2017-03-16
      相关资源
      最近更新 更多