【问题标题】:python lxml etree parsing an fvdl filepython lxml etree解析fvdl文件
【发布时间】:2013-08-06 16:03:45
【问题描述】:

该文件包含以下几行。

<?xml version="1.0" encoding="UTF-8"?>
<FVDL xmlns="xmlns://www.fortifysoftware.com/schema/fvdl" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.9" xsi:type="FVDL">`
<CreatedTS date="2013-08-06" time="11:8:48" />`

我正在尝试读取 FVDL 中的版本标签。我正在使用 lxml etree,而我的代码 sn-p 是

from lxml import etree
with open(os.path.join(analysis,"merged-results.fvdl") ,"r") as file_handle:
  context = etree.parse(file_handle)
  ver = context.xpath('//FVDL')
  print ver

这在解析标准 xml 文件之前已经起作用。但是上面提到的文件失败了。(ver在执行结束时是一个空列表)

【问题讨论】:

    标签: python xml-parsing lxml xml.etree


    【解决方案1】:

    @falsetru 答案的替代方案

    (通过“试图读取版本标签”,我理解“版本属性”(可能不是你想要的))

    显式注册 fvdl 命名空间,在“fvdl”前缀下:

    ver = context.xpath('//fvdl:FVDL/@version',
              namespaces={"fvdl": "xmlns://www.fortifysoftware.com/schema/fvdl"})
    

    或者,风险更大,如果你知道你想要来自根节点的version 属性

    ver = context.xpath('/*/@version')
    

    两者都给['1.9']

    【讨论】:

    • 如果你不知道匿名命名空间(它是 context.nsmap 中的 None 条目),你可以这样做:namespaces = dict((k or 'fvdl', v) for k, v in context.nsmap.iteritems())
    【解决方案2】:
    context = etree.parse(file_handle)
    ver = context.getroot()
    print ver.attrib['version']
    
    output:'1.9'
    

    【讨论】:

      【解决方案3】:

      使用[local-name()=...]:

      ver = context.xpath('//*[local-name()="FVDL"]')
      

      【讨论】:

        猜你喜欢
        • 2020-08-28
        • 2017-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-09
        • 1970-01-01
        • 2014-04-29
        • 2014-03-27
        相关资源
        最近更新 更多