2011-03-30 64 views
0

我正嘗試使用縮小網站縮略圖的Web服務。他們有一個API返回XML,告訴你是否可以創建站點縮略圖。我正在嘗試使用ElementTree解析xml,但不知道如何獲取我需要的信息。這裏是一個XML響應的例子:如何解析用ElementTree收縮web 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」,則會出現「期望的路徑分隔符」語法錯誤。有沒有辦法獲得狀態碼?

+0

如果你表明你正在使用的代碼... – 2011-03-30 01:45:40

回答

1

哎呀命名空間....試試這個:

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

(見示例XML的2號線)

然後,當你想要一個像stw:StatusCode標籤,使用STW_PREFIX + "StatusCode"

更新:該XML響應不是最出色的設計。從單個例子​​中不可能猜測是否可以有超過1個二級節點。請注意,每個第三級節點都有一個「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' {} 
+0

在Python 2.7+,您可以使用register_namespace(HTTP它可以幫助://docs.python。 org/library/xml.etree.elementtree.html#xml.etree.ElementTree.register_namespace)來簡化調用命名空間前綴的語法。 – 2011-03-30 02:43:57

+0

@Liza Daly:文檔提到了序列化。它如何幫助解析現有的XML文檔? – 2011-03-30 05:29:16