https://docs.python.org/2/library/xml.etree.elementtree.html
http://stackoverflow.com/questions/15643094/python-version-2-7-xml-elementtree-how-to-iterate-through-certain-elements-of
http://stackoverflow.com/questions/9177360/updating-xml-elements-and-attribute-values-using-python-etree
http://stackoverflow.com/questions/14440375/how-to-add-an-element-to-xml-file-by-using-elementtree
# Node name = '.tag'
# Node attribute = '.attrib'
# Node value = '.text'
#
Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:
# XML Handling
[To write an XML file using Etree: tree.write("/tmp/" + executionID +".xml") ]
import xml.etree.ElementTree as ET
# Get element object:
# First get root element
# From File:
tree = ET.parse('country_data.xml')
root = tree.getroot()
# From xml string
xml_str = '''
<project>
<publishers>
...
...
</publishers>
<project>
root = ET.fromstring(xml_str)
updated_xml_str = ET.tostring(root)
====
# Get desired element object to set using XPath: text or attribute
DESCRIPTION_PATH = './publishers/hudson.plugins.descriptionsetter.DescriptionSetterPublisher/description'
DESCRIPTION_PATH is path relative to the root element (in case of jenkins, the root element is project)
root.find(DESCRIPTION_PATH).text = 'Updated Text'
# Create new element:
# create new child object:
new_element_object = 'ET.Element("new_element")
# Add the new_element_object to the existing element you want;
for root:
root.append(new_element_object)
OR (a one-liner):
root.find(DESCRIPTION_PATH).append('new_element_object')
OR (use Subelement);
ET.SubElement(root.find(DESCRIPTION_PATH), tag='new_element')
ET.SubElement(root.find(DESCRIPTION_PATH), 'new_element') # Without tag variable
OR (with text setting)
ET.SubElement(root.find(DESCRIPTION_PATH), 'new_element').text = 'HELLO MAN JEE!'
# element.findall(path) : gives a list of all elements at the given path relative to the element it is operated on
it gives list of all the element: to find the text, you need to use the method 'find'
y = root.findall('builders/hudson.tasks.Shell')
for x in y:
print x.find('command').text
No comments:
Post a Comment