2013-12-16 86 views
0

我想解析從RESTful接口收到的xml數據。在錯誤情況下(當查詢不會導致服務器上的任何內容時),我返回以下文本。現在,我想解析這個字符串來搜索在下面給出的例子中出現在第五行的status的值。我怎樣才能找到狀態是否存在,如果存在,那麼它的價值是什麼。如何使用python在xml中查找特定標籤elemnet中的值?

content = """ 
<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?> 
<ops:world-patent-data xmlns="http://www.epo.org/exchange" xmlns:ops="http://ops.epo.org" xmlns:xlink="http://www.w3.org/1999/xlink"> 
    <ops:meta name="elapsed-time" value="3"/> 
    <exchange-documents> 
     <exchange-document system="ops.epo.org" country="US" doc-number="20060159695" status="not found"> 
      <bibliographic-data> 
       <publication-reference> 
        <document-id document-id-type="epodoc"> 
         <doc-number>US20060159695</doc-number> 
        </document-id> 
       </publication-reference> 
       <parties/> 
      </bibliographic-data> 
     </exchange-document> 
    </exchange-documents> 
</ops:world-patent-data> 
""" 
import xml.etree.ElementTree as ET 
root = ET.fromstring(content) 
res = root.iterfind(".//{http://www.epo.org/exchange}exchange-documents[@status='not found']/..") 

回答

1

只需使用BeautifulSoup:

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(open('xml.txt', 'r')) 

print soup.findAll('exchange-document')["status"] 

#> not found 

如果你存儲在一個文件中的每個XML輸出,將重複他們有用:

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(open('xml.txt', 'r')) 

for tag in soup.findAll('exchange-document'): 
    print tag["status"] 

#> not found 

這將顯示從每一個[狀態]標籤[交換文件]元素。

另外,如果你想只可使用狀態,你應該做的:

for tag in soup.findAll('exchange-document'): 
    if tag["status"] not in "not found": 
     print tag["status"] 
0

試試這個:

from xml.dom.minidom import parse 
xmldoc = parse(filename) 
elementList = xmldoc.getElementsByTagName(tagName) 

elementList將包含您指定的標籤名的所有元素,那麼你可以通過這些迭代。

相關問題