如何使用python在xml中查找特定标记元素中的值?
我试图解析从RESTful接口接收的xml数据。在错误条件下(当查询没有在服务器上产生任何结果时),将返回以下文本。现在,我想解析这个字符串来搜索下面示例中第五行中的如何使用python在xml中查找特定标记元素中的值?,python,xml,Python,Xml,我试图解析从RESTful接口接收的xml数据。在错误条件下(当查询没有在服务器上产生任何结果时),将返回以下文本。现在,我想解析这个字符串来搜索下面示例中第五行中的status值。我如何找到状态是否存在,如果存在,那么它的价值是什么 content = """ <?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/3.0/style/exchange.xsl"?> &l
status
值。我如何找到状态是否存在,如果存在,那么它的价值是什么
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']/..")
content=”“”
US20060159695
"""
将xml.etree.ElementTree作为ET导入
root=ET.fromstring(内容)
res=root.iterfind(“)//{http://www.epo.org/exchange}交换文档[@status='notfound']/..)
试试这个:
from xml.dom.minidom import parse
xmldoc = parse(filename)
elementList = xmldoc.getElementsByTagName(tagName)
elementList
将包含具有指定标记名的所有元素,然后您可以迭代这些元素。只需使用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
这将显示[exchange document]元素中的每个[status]标记
另外,如果您只想要有用的状态,您应该:
for tag in soup.findAll('exchange-document'):
if tag["status"] not in "not found":
print tag["status"]