Skip to content

Instantly share code, notes, and snippets.

@josephcoombe
Last active April 2, 2019 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephcoombe/307125443cacf3a6728d576a6367bff5 to your computer and use it in GitHub Desktop.
Save josephcoombe/307125443cacf3a6728d576a6367bff5 to your computer and use it in GitHub Desktop.
Python xml.etree with XPath
# Python xml.etree with xpath
#
# References:
# The ElementTree XML API: https://docs.python.org/2/library/xml.etree.elementtree.html
import xml.etree
from xml.etree.ElementTree import Element
from xml.etree import ElementTree as ET
from xml.dom import minidom
import lxml # Apparently this is faster / better
if __name__ == '__main__':
count = 0
t = ET.parse('test_file.xml')
r = t.getroot()
for value in r.findall(".//model[@kind='GenericDomainModelPort']"
+ "/attribute[@kind='Type'][value='topic']"
+ "/../attribute[@kind='GenericAttribute7']"
+ "/value"):
value.text = "new_value"
count += 1
# Equivalent to
# for model in r.iter('model'):
# if model.get('kind') is not None and model.get('kind') == "GenericDomainModelPort":
# for attribute in model.iter('attribute'):
# if attribute.get('kind') is not None and attribute.get('kind') == "Type":
# for value in attribute.iter('value'):
# if value.text == "topic":
# count += 1
rough_urdf_string = ET.tostring(r)
reparsed_urdf_string = minidom.parseString(rough_urdf_string)
with open('test_file.xml', 'w') as output_file:
output_file.write(reparsed_urdf_string.toprettyxml(indent=' '))
print("Total Count: {}".format(count))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment