xml 使用 lxml 的解析器问题 python
xml parser issue using lxml python
我正在使用特定于服务器的数据并想解析我的 xml 文件中的数据 "measTypes"。由于我的 xml 文件(命名空间)中的一些头数据,我无法解析数据,我的代码失败了,你能帮我在我的 xml 数据中获取 "measTypes" 吗?
我正在使用下面的代码,但它失败了,因为 measInfo 没有值:
from lxml import etree
tree = etree.parse(open("BLRNCH03.xml"))
measInfo = tree.xpath('//measInfo[@measInfoId="67109488"]')[0]
print(measInfo)
这是我的 xml 数据:
<?xml version="1.0" encoding="UTF-8"?>
<measCollecFile xmlns="http://latest/nmc-omc/cmNrm.doc#measCollec" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://latest/nmc-omc/cmNrm.doc#measCollec schema\pmResultSchedule.xsd">
<fileHeader fileFormatVersion="32.435 V7.2" vendorName="Huawei">
<fileSender elementType="BSC6910 UMTS"/>
<measCollec beginTime="2018-04-22T00:00:00+04:30"/>
</fileHeader>
<measData>
<measInfo measInfoId="67109481">
<measTypes>67194793 67194794 67194795 67194796 </measTypes>
</measInfo>
<measData>
<fileFooter>
<measCollec endTime="2018-04-22T01:00:00+04:30"/>
</fileFooter>
</measCollecFile>
只需 bind the default namespace to a prefix 并在 .xpath()
调用中使用它。
我使用了前缀 mc
,但您可以使用不同的前缀。
示例...
from lxml import etree
namespaces = {"mc": "http://latest/nmc-omc/cmNrm.doc#measCollec"}
tree = etree.parse("BLRNCH03.xml")
measTypes = tree.xpath("//mc:measInfo[@measInfoId='67109481']/mc:measTypes",
namespaces=namespaces)[0]
print(measTypes)
这将打印如下内容:
<Element {http://latest/nmc-omc/cmNrm.doc#measCollec}measTypes at 283e638>
我正在使用特定于服务器的数据并想解析我的 xml 文件中的数据 "measTypes"。由于我的 xml 文件(命名空间)中的一些头数据,我无法解析数据,我的代码失败了,你能帮我在我的 xml 数据中获取 "measTypes" 吗?
我正在使用下面的代码,但它失败了,因为 measInfo 没有值:
from lxml import etree
tree = etree.parse(open("BLRNCH03.xml"))
measInfo = tree.xpath('//measInfo[@measInfoId="67109488"]')[0]
print(measInfo)
这是我的 xml 数据:
<?xml version="1.0" encoding="UTF-8"?>
<measCollecFile xmlns="http://latest/nmc-omc/cmNrm.doc#measCollec" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://latest/nmc-omc/cmNrm.doc#measCollec schema\pmResultSchedule.xsd">
<fileHeader fileFormatVersion="32.435 V7.2" vendorName="Huawei">
<fileSender elementType="BSC6910 UMTS"/>
<measCollec beginTime="2018-04-22T00:00:00+04:30"/>
</fileHeader>
<measData>
<measInfo measInfoId="67109481">
<measTypes>67194793 67194794 67194795 67194796 </measTypes>
</measInfo>
<measData>
<fileFooter>
<measCollec endTime="2018-04-22T01:00:00+04:30"/>
</fileFooter>
</measCollecFile>
只需 bind the default namespace to a prefix 并在 .xpath()
调用中使用它。
我使用了前缀 mc
,但您可以使用不同的前缀。
示例...
from lxml import etree
namespaces = {"mc": "http://latest/nmc-omc/cmNrm.doc#measCollec"}
tree = etree.parse("BLRNCH03.xml")
measTypes = tree.xpath("//mc:measInfo[@measInfoId='67109481']/mc:measTypes",
namespaces=namespaces)[0]
print(measTypes)
这将打印如下内容:
<Element {http://latest/nmc-omc/cmNrm.doc#measCollec}measTypes at 283e638>