Python -lxml xpath返回空列表

时间:2017-08-14 07:16:33

标签: python xml xpath lxml

我正在阅读xliff文件并计划检索特定元素。我尝试使用

打印所有元素
from lxml import etree
with open('path\to\file\.xliff', 'r',encoding = 'utf-8') as xml_file:
        tree = etree.parse(xml_file)
    root = tree.getroot()
for element in root.iter():
        print("child", element)

输出

child <Element {urn:oasis:names:tc:xliff:document:2.0}segment at 0x6b8f9c8>
child <Element {urn:oasis:names:tc:xliff:document:2.0}source at 0x6b8f908>

当我尝试获取特定元素时(在此处有许多帖子的帮助下) - 源标记

segment = tree.xpath('{urn:oasis:names:tc:xliff:document:2.0}segment')
print(segment)

它返回一个空列表。有人能告诉我如何正确检索它。

输入:

<?xml version='1.0' encoding='UTF-8'?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:2.0" version="2.0">

   <segment id = 1>
    <source>
      Hello world
     </source>
  </segment>
  <segment id = 2 >
    <source>
       2nd statement
      </source>
     </segment>
 </xliff>

我想获取segment及其相应来源的值

1 个答案:

答案 0 :(得分:0)

此代码,

tree.xpath('{urn:oasis:names:tc:xliff:document:2.0}segment')
lxml(“lxml.etree.XPathEvalError:Invalid expression”)不接受

。您需要使用findall()

以下工作(在XML示例中,segment元素是xliff的子元素):

from lxml import etree

tree = etree.parse("test.xliff")   # XML in the question; ill-formed attributes corrected
segment = tree.findall('{urn:oasis:names:tc:xliff:document:2.0}segment')
print(segment)

然而,真正的XML显然更复杂(segment不是xliff的直接子)。然后,您需要添加.//来搜索整个树:

segment = tree.findall('.//{urn:oasis:names:tc:xliff:document:2.0}segment')