1

Windows 7のPyDevプラグインを使用して、EclipseでPython 3.3を使用しています。

XPath と LXML を使用して XML ファイルを解析する必要があります。静的 XPath 式を使用すると機能しますが、変数を使用する必要がありますが、式で変数を使用すると機能しません。

このコードを使用する場合:

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'.

これどうやってするの?

ありがとう

4

2 に答える 2

1

一重引用符を削除してみてください。変数の引用が1レベル多すぎると思いますpath。私はただ使用しますpath = "//" + ns + header

于 2013-07-12T10:48:12.613 に答える
0

リテラルの引用符で文字列を作成しています。必要ありません'。文字を省略します。

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

または文字列フォーマットを使用します:

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

元のバージョンは次のものと同等でした:

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

(余分な一重引用符に注意してください)。

于 2013-07-12T10:45:40.173 に答える