【发布时间】:2013-07-02 00:47:16
【问题描述】:
我正在使用 ElementTree 解析下面显示的 xml,但在代码中出现错误 Invalid Predicate。
基本上,我试图找到具有特定 pin 属性名称的元素 connect。
XML
<deviceset>
<devices>
<device name="">
<connects>
<connect gate="G$1" pin="+15V_DC" pad="7"/>
<connect gate="G$1" pin="FB" pad="3"/>
<connect gate="G$1" pin="ICOM" pad="4"/>
<connect gate="G$1" pin="IN+" pad="5"/>
<connect gate="G$1" pin="IN-" pad="6"/>
<connect gate="G$1" pin="OUT_HI" pad="1"/>
<connect gate="G$1" pin="OUT_LO" pad="9"/>
<connect gate="G$1" pin="PWRCOM" pad="2"/>
</connects>
</device>
</devices>
</deviceset>
Python代码
# Imports
import xml.etree as ET
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
# Open a file sent to the function
file = open(os.path.join(__location__, file));
tree = ET.parse(file)
root = tree.getroot()
deviceset = root.find ('deviceset')
deviceset.find('devices').find('device').find('connects').**findall("./connect[@pin = \"FB\"]")**
问题似乎是 XPATH 样式路径(上面突出显示)。
关于我做错了什么有什么想法吗?
【问题讨论】:
-
无论你是2.x还是3.x,都没有
xml.etree.parse这样的功能。你的意思是from xml.etree import ElementTree as ET?最重要的是,您发布的代码甚至会在运行之前引发缩进错误。您能否给我们实际的、可运行的代码来显示您的错误?这使得调试变得容易得多。 -
另外,ElementTree 不会在这个 XML 中给你任何这样的错误,因为它会放弃解析它,因为
<device>标记在它甚至可以到达那部分之前永远不会接近的代码。而且,如果你解决了这个问题,因为<deviceset>是实际的根音,root.find('deviceset')将返回None。而且,如果你解决了这个问题,你会在.**上得到一个语法错误。 -
@abarnert 哦,对不起,忽略我的导入——我正在改变事情,实际上是指
xml.etree import ElementTree as ET
标签: python xpath elementtree