【问题标题】:How to parse shrink the web xml with ElementTree如何使用 ElementTree 解析收缩 web xml
【发布时间】:2011-03-30 01:20:57
【问题描述】:

我正在尝试使用缩小网站缩略图的 Web 服务。他们有一个返回 XML 的 API,告诉您是否可以创建站点缩略图。我正在尝试使用 ElementTree 来解析 xml,但不确定如何获取我需要的信息。以下是 XML 响应的示例:

<?xml version="1.0" encoding="UTF-8"?> 
<stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stwresponse.xsd">
    <stw:Response>
        <stw:ThumbnailResult>
            <stw:Thumbnail Exists="false"></stw:Thumbnail>
            <stw:Thumbnail Verified="false">fix_and_retry</stw:Thumbnail>
        </stw:ThumbnailResult>
        <stw:ResponseStatus>
            <stw:StatusCode>Blank Detected</stw:StatusCode>
        </stw:ResponseStatus>
        <stw:ResponseTimestamp>
            <stw:StatusCode></stw:StatusCode>
        </stw:ResponseTimestamp>
        <stw:ResponseCode>
            <stw:StatusCode></stw:StatusCode>
        </stw:ResponseCode>
        <stw:CategoryCode>
            <stw:StatusCode>none</stw:StatusCode>
        </stw:CategoryCode>
        <stw:Quota_Remaining>
            <stw:StatusCode>1</stw:StatusCode>
        </stw:Quota_Remaining>
    </stw:Response>
</stw:ThumbnailResponse>

我需要获取“stw:StatusCode”。如果我尝试在“stw:StatusCode”上进行查找,则会收到“预期路径分隔符”语法错误。有没有办法只获取状态码?

【问题讨论】:

  • 如果您要显示您正在使用的代码可能会有所帮助...

标签: python elementtree


【解决方案1】:

Grrr 命名空间 ....试试这个:

STW_PREFIX = "{http://www.shrinktheweb.com/doc/stwresponse.xsd}"

(参见示例 XML 的第 2 行)

那么当你想要stw:StatusCode这样的标签时,使用STW_PREFIX + "StatusCode"

更新:XML 响应并不是最出色的设计。无法从您的单个示例中猜测是否可以有超过 1 个 2 级节点。请注意,每个 3 级节点都有一个“StatusCode”子节点。下面是一些粗略的代码,向您展示 (1) 为什么需要 STW_PREFIX caper (2) 可用信息的摘录。

import xml.etree.cElementTree as et
def showtag(elem):
    return repr(elem.tag.rsplit("}")[1])
def showtext(elem):
    return None if elem.text is None else repr(elem.text.strip())
root = et.fromstring(xml_response) # xml_response is your input string
print repr(root.tag) # see exactly what tag is in the element
for child in root[0]:
    print showtag(child), showtext(child)
    for gc in child:
        print "...", showtag(gc), showtext(gc), gc.attrib

结果:

'{http://www.shrinktheweb.com/doc/stwresponse.xsd}ThumbnailResponse'
'ThumbnailResult' ''
... 'Thumbnail' None {'Exists': 'false'}
... 'Thumbnail' 'fix_and_retry' {'Verified': 'false'}
'ResponseStatus' ''
... 'StatusCode' 'Blank Detected' {}
'ResponseTimestamp' ''
... 'StatusCode' None {}
'ResponseCode' ''
... 'StatusCode' None {}
'CategoryCode' ''
... 'StatusCode' 'none' {}
'Quota_Remaining' ''
... 'StatusCode' '1' {}

【讨论】:

  • 在 Python 2.7+ 中,您可以使用 register_namespace (docs.python.org/library/…) 来简化调用命名空间前缀的语法。
  • @Liza Daly:文档提到了序列化。它如何帮助解析现有的 XML 文档?
猜你喜欢
  • 1970-01-01
  • 2021-02-06
  • 2017-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-08
  • 2014-02-06
相关资源
最近更新 更多