使用lxml-python的xml解析器问题

2024-05-19 23:02:56 发布

您现在位置: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>

Tags: 文件数据代码treehttpxmllatestetree
1条回答
网友
1楼 · 发布于 2024-05-19 23:02:56

只需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>

相关问题 更多 >