How to modify a tag text value based on its sibling tag text value in xml with python?
Question: For Eg:

    
    
    <parameterDefinitions>
            <hudson.model.StringParameterDefinition>
              <name>name</name>
              <description></description>
              <defaultValue>abc</defaultValue>
            </hudson.model.StringParameterDefinition>
            <hudson.model.BooleanParameterDefinition>
              <name>branch</name>
              <description></description>
              <defaultValue>true</defaultValue>
            </hudson.model.BooleanParameterDefinition>
    </parameterDefinitions>
    

Above given is the small part of XML file which am getting from the Jenkins
server. I need to modify the default value(abc and true for the above eg) of
the parameters based on its respective name(name and branch).

Have read about MiniDom, Element and ElementTree but couldn't figure out the
exact api. Can anyone help me out with this. Thanks in advance.


Answer: Simplest try may be using `lxml.etree` and grabbing the node by `xpath` (i.e.
`//hudson.model.StringParameterDefinition/defaultValue` here) to be changed as
below and changing properly-

    
    
    from lxml import etree as et
    
    data = """<parameterDefinitions>
            <hudson.model.StringParameterDefinition>
              <name>name</name>
              <description></description>
              <defaultValue>abc</defaultValue>
            </hudson.model.StringParameterDefinition>
            <hudson.model.BooleanParameterDefinition>
              <name>branch</name>
              <description></description>
              <defaultValue>true</defaultValue>
            </hudson.model.BooleanParameterDefinition>
    </parameterDefinitions>"""
    
    tree = et.fromstring(data)
    w = tree.xpath("//hudson.model.StringParameterDefinition/defaultValue")
    w[0].text = "changed"# here w is a list
    print et.tostring(tree,pretty_print=True)
    

Output-

    
    
    <parameterDefinitions>
            <hudson.model.StringParameterDefinition>
              <name>name</name>
              <description/>
              <defaultValue>changed</defaultValue>
            </hudson.model.StringParameterDefinition>
            <hudson.model.BooleanParameterDefinition>
              <name>branch</name>
              <description/>
              <defaultValue>true</defaultValue>
            </hudson.model.BooleanParameterDefinition>
    </parameterDefinitions>
    

