[英]Print attribute value based on condition attribute in same element (XML Python)
I have a xml file like this: 我有一个这样的xml文件:
<button_map>
<button id="abs_axis_11" label="">
<device type="keyboard" id="0" name=""/>
<event type="button" id="g"/>
</button>
<button id="abs_axis_16" label="Melee">
<device type="keyboard" id="0" name=""/>
<event type="button" id="v"/>
/button>
<button id="abs_axis_11" label="">
<device type="joystick" id="0" name="Controller"/>
<event type="button" id="9"/>
</button>
</button_map>
The condition is if button id = "abs_axis_11" && name = "" : print output = g, but I don't find a way to remove id = 9 in result output (using Python) 条件是如果按钮id =“ abs_axis_11” && name =“”:打印输出= g,但我找不到在结果输出中删除id = 9的方法(使用Python)
My working code: 我的工作代码:
for event in root.findall('/button_map/button[@id="abs_axis_11"][device[@name=""]]/event'):
button = event.get('id')
print button
I had to take some liberty with the example below, as the data and code you provided isn't a complete, working example (for future reference, try following these instructions ). 我不得不对下面的示例采取一些自由态度,因为您提供的数据和代码不是一个完整的,可以正常工作的示例(以供将来参考,请尝试按照以下说明进行操作 )。
Assumptions: 假设:
xml.etree.ElementTree
module xml.etree.ElementTree
模块 Based on those assumptions I put together the following: 基于这些假设,我总结了以下内容:
#!/usr/bin/python
import xml.etree.ElementTree as ET
XML_DATA = """
<root>
<button_map>
<button id="abs_axis_11" label="">
<device type="keyboard" id="0" name=""/>
<event type="button" id="g"/>
</button>
<button id="abs_axis_16" label="Melee">
<device type="keyboard" id="0" name=""/>
<event type="button" id="v"/>
</button>
<button id="abs_axis_11" label="">
<device type="joystick" id="0" name="Controller"/>
<event type="button" id="9"/>
</button>
</button_map>
</root>
"""
tree = ET.ElementTree(ET.fromstring(XML_DATA))
for event in tree.findall(
'./button_map/button[@id="abs_axis_11"]/device[@name=""]/../event'):
print "Result: %s" % (event)
print "Event ID: %s" % event.get('id')
The output of this script is: 该脚本的输出为:
$ python python-xml.py
Result: <Element 'event' at 0x7efd53f8c610>
Event ID: g
Here's are some pointers regarding your XPath query: 以下是有关XPath查询的一些提示:
device
is a child element not an attribute of button
. device
是一个子元素,不是button
的属性。 Therefore I removed it from the brackets (which was causing an invalid predicate
error for me, and specified it an element in the hierarchy invalid predicate
错误,并在层次结构中将其指定为元素 ..
to navigate to parent element of device
(ie button
) and then down to it's child element event
..
导航至device
父元素(即button
),然后向下至其子元素event
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.