简体   繁体   中英

Print attribute value based on condition attribute in same element (XML Python)

I have a xml file like this:

<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)

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:

  • you're using the xml.etree.ElementTree module
  • the XML snippet you provided is a subset of the overall message you're parsing

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:

  • device is a child element not an attribute of 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
  • because of the above, I used .. to navigate to parent element of device (ie button ) and then down to it's child element event

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM