我正在尝试像这样解析一个 xml
<document>
<pages>
<page>
<paragraph>XBV</paragraph>
<paragraph>GHF</paragraph>
</page>
<page>
<paragraph>ash</paragraph>
<paragraph>lplp</paragraph>
</page>
</pages>
</document>
这是我的代码
import xml.etree.ElementTree as ET
tree = ET.parse("../../xml/test.xml")
root = tree.getroot()
path="./pages/page/paragraph[text()='GHF']"
print root.findall(path)
但是我得到一个错误
print root.findall(path)
File "X:\Anaconda2\lib\xml\etree\ElementTree.py", line 390, in findall
return ElementPath.findall(self, path, namespaces)
File "X:\Anaconda2\lib\xml\etree\ElementPath.py", line 293, in findall
return list(iterfind(elem, path, namespaces))
File "X:\Anaconda2\lib\xml\etree\ElementPath.py", line 263, in iterfind
selector.append(ops[token[0]](next, token))
File "X:\Anaconda2\lib\xml\etree\ElementPath.py", line 224, in prepare_predicate
raise SyntaxError("invalid predicate")
SyntaxError: invalid predicate
我的 xpath 有什么问题?
跟进
谢谢 faltru,您的解决方案奏效了。我有跟进。现在,我想获取文本 GHF
段落之前的所有段落元素。所以在这种情况下,我只需要 XBV
元素。我想忽略 ash
和 lplp
。我想这样做的一种方法是
result = []
for para in root.findall('./pages/page/'):
t = para.text.encode("utf-8", "ignore")
if t == "GHF":
break
else:
result.append(para)
但是有更好的方法吗?
最佳答案
ElementTree's XPath support is limited.使用其他库,如 lxml
:
import lxml.etree
root = lxml.etree.parse('test.xml')
path="./pages/page/paragraph[text()='GHF']"
print root.xpath(path)
关于Python XPath 语法错误 : invalid predicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830821/