我试图用lxml解析一个包含多个名称空间的XML文档,但我一直在让findall()方法返回一些内容。在
我的XML:
<MeasurementRecords xmlns="http://www.company.com/common/rsp/2012/07"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.company.com/common/rsp/2012/07 RSP_EWS_V1.6.xsd">
<HistoryRecords>
<ValueItemId>100_0000100004_3788_Resource-0.customId_WSx Data Precip Type</ValueItemId>
<List>
<HistoryRecord>
<Value>60</Value>
<State>Valid</State>
<TimeStamp>2016-04-20T12:40:00Z</TimeStamp>
</HistoryRecord>
</List>
</HistoryRecords>
<HistoryRecords>
</MeasurementRecords>
我的代码:
^{pr2}$给出:
ValueError: empty namespace prefix is not supported in ElementPath
我在读了this之后尝试了一些实验:
>>> root.nsmap
{'xsi': 'http://www.w3.org/2001/XMLSchema-instance', None: http://www.company.com/common/rsp/2012/07'}
>>> nsmap['foo']=nsmap[None]
>>> nsmap.pop(None)
'http://www.company.com/common/rsp/2012/07'
>>> nsmap
{'xsi': 'http://www.w3.org/2001/XMLSchema-instance', 'foo': 'http://www.company.com/common/rsp/2012/07'}
>>> tree.xpath("//MeasurementRecords", namespaces=nsmap)
[]
>>> tree.xpath('/foo:MeasurementRecords', namespaces=nsmap)
[<Element {http://www.company.com/common/rsp/2012/07}MeasurementRecords at 0x6ffffda5290>]
>>> tree.xpath('/foo:MeasurementRecords/HistoryRecords', namespaces=nsmap)
[]
但这似乎没有帮助。在
所以,更多的实验:
>>> tree.findall('//{http://www.company.com/common/rsp/2012/07}MeasurementRecords')
[]
>>> print root
<Element {http://www.company.com/common/rsp/2012/07}MeasurementRecords at 0x6ffffda5290>
>>> print tree
<lxml.etree._ElementTree object at 0x6ffffda5368>
>>> for node in tree.iter():
... print node
...
<Element {http://www.company.com/common/rsp/2012/07}MeasurementRecords at 0x6ffffda5290>
<Element {http://www.company.com/common/rsp/2012/07}HistoryRecords at 0x6ffffda5cf8>
<Element {http://www.company.com/common/rsp/2012/07}ValueItemId at 0x6ffffda5f38>
...etc...
>>> tree.findall("//HistoryRecords", namespaces=nsmap)
[]
>>> tree.findall("//foo:MeasurementRecords/HistoryRecords", namespaces=nsmap)
[]
我被难住了。我不知道怎么了。在
如果你从这个开始:
这将无法找到任何元素。。。在
^{pr2}$…但这是因为
root
是一个MeasurementRecords
元素;它 不包含任何MeasurementRecords
元素。另一方面 hand,下面的方法很好:使用
xpath
方法,可以执行以下操作:所以:
findall
和find
方法需要{...namespace...}ElementName
语法。在xpath
方法需要名称空间前缀(ns:ElementName
),它在提供的namespaces
映射中查找这些前缀。前缀不必与原始文档中使用的前缀匹配,但命名空间url必须匹配。在所以这是可行的:
或者这个工程:
相关问题 更多 >
编程相关推荐