【问题标题】:How to use a variable in LXML XPath Expression如何在 LXML XPath 表达式中使用变量
【发布时间】:2013-07-10 21:22:41
【问题描述】:

我在 Eclipse 中使用 Python 3.3 和 Windows 7 上的 PyDev 插件。

我需要使用 XPath 和 LXML 解析 XML 文件。如果我使用静态 XPath 表达式,它可以工作,但我需要使用变量 one,但是当我在表达式中使用变量时,它不起作用。

如果我使用此代码:

xml = etree.parse(fullpath).getroot()
tree = etree.ElementTree(xml)

nsmap = {'xis' : 'http://www.xchanging.com/ACORD4ALLEDI/1',
         'ns' : 'http://www.ACORD.org/standards/Jv-Ins-Reinsurance/1' }

p = tree.xpath('//xis:Line', namespaces=nsmap)
print (p)
for e in p:
    print(e.tag, e.text)

它按我的意愿工作,print(p) 返回

 [<Element {http://www.xchanging.com/ACORD4ALLEDI/1}LloydsProcessingCode at 0x2730350>]

但如果我将其更改为:

xml = etree.parse(fullpath).getroot()
tree = etree.ElementTree(xml)

nsmap = {'xis' : 'http://www.xchanging.com/ACORD4ALLEDI/1',
         'ns' : 'http://www.ACORD.org/standards/Jv-Ins-Reinsurance/1' }
header = 'Jv-Ins-Reinsurance'
ns = 'xis:'
path = "'//" + ns + header + "'"    
p = tree.xpath('%s' % path, namespaces=nsmap)
print ('p = %s' % p)
for e in p:
    print(e.tag, e.text)

print(p) 返回:

p = //xis:Jv-Ins-Reinsurance

我得到一个错误:AttributeError: 'str' object has no attribute 'tag'

我该怎么做?

谢谢

【问题讨论】:

    标签: python xpath python-3.x lxml


    【解决方案1】:

    您可以尝试删除单引号吗?我认为您在 path 变量中引用的级别太多了。我只会使用path = "//" + ns + header

    【讨论】:

    【解决方案2】:

    您正在构建一个带有文字引号的字符串。您不需要,省略 ' 字符。

    path = "//" + ns + header
    p = tree.xpath(path, namespaces=nsmap)
    

    或使用字符串格式:

    path = "//{}{}".format(ns, header)
    p = tree.xpath(path, namespaces=nsmap)
    

    您的原始版本相当于:

    path = "'//xis:Jv-Ins-Reinsurance'"
    

    (注意额外的单引号字符)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-14
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-31
      相关资源
      最近更新 更多