如果通过搜索和阅读lxml文档可以轻松回答这个问题我很抱歉,但我试图无济于事。
我一直经常使用lxml的findall来查询XML文件。最近,我需要使用通配符来提取我需要的数据。这导致我使用Xpath。
我设法使用ETXPath而不是Xpath。我很困惑为什么。 XML文件的摘要
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DC xmlns="http://tradefinder.db.com/Schemas/MEL/MelHorizon_0_4_2.xsd">
<Header>
<FileName>DBL_MPA_Gap_PRD_2017-06-01T07-50-52.xml</FileName>
<ValidityDate>2017-05-31</ValidityDate>
<Version>0.42</Version>
<NoOfRecords>17228</NoOfRecords>
</Header>
<Overviews>
<OverviewLevelTimeStamp>
<Identifier>Z 1 Index, TRADE</Identifier>
<Level>2.2120000000000002</Level>
<Timestamp>09:00:00.000</Timestamp>
</OverviewLevelTimeStamp>
</Overviews>
</DC>
我的python代码用于提取
findshiz = ETXPath("//" + namespace + "DC/" + namespace + "Overviews/" + namespace + "OverviewLevelTimeStamp[" + namespace + "Identifier= 'Z 1 Index, TRADE']")
required_nodes = findshiz(gap_xml)
其中“gap_xml”=解析文件。
此代码有效。出于某种原因,当我尝试使用xpath时,它没有。这涉及到我只需用xpath重命名ETXPath。之所以是因为我需要使用通配符,所以不是“Z 1 Index,TRADE”,而是Z 1 Index *。
谢谢,让我知道无论如何要改进这个问题。
答案 0 :(得分:1)
contains(., "Z 1 Index,")
就像说*Z1 Index*
,这是一次substring
搜索。
以下是使用contains的示例,它类似于来自xpath的通配符并映射使用的命名空间:
: import lxml.etree as etree
: xstring = """
...: <DC xmlns="http://tradefinder.db.com/Schemas/MEL/MelHorizon_0_4_2.xsd">
...: <Header>
...: <FileName>DBL_MPA_Gap_PRD_2017-06-01T07-50-52.xml</FileName>
...: <ValidityDate>2017-05-31</ValidityDate>
...: <Version>0.42</Version>
...: <NoOfRecords>17228</NoOfRecords>
...: </Header>
...: <Overviews>
...: <OverviewLevelTimeStamp>
...: <Identifier>Z 1 Index, TRADE</Identifier>
...: <Level>2.2120000000000002</Level>
...: <Timestamp>09:00:00.000</Timestamp>
...: </OverviewLevelTimeStamp>
...: </Overviews>
...: </DC>"""
xstring = etree.fromstring(xstring)
nsmap = {'ns': 'http://tradefinder.db.com/Schemas/MEL/MelHorizon_0_4_2.xsd'}
print xstring.xpath('//ns:OverviewLevelTimeStamp[ns:Identifier[contains(., "Z 1 Index,")]]', namespaces=nsmap)
结果
[<Element {http://tradefinder.db.com/Schemas/MEL/MelHorizon_0_4_2.xsd}OverviewLevelTimeStamp at 0x10647aa70>]
请注意lxml xpath返回一个列表,因此您必须从列表中提取匹配的节点。