1

There's an XML something like this

    <OUTER>
            <TYPE>FIRST</TYPE>
            <FIELD1>1</FIELD1>
            <ID>55056</ID>
            <TASK>
                <FILE>
                    <OPTIONS>1</OPTIONS>
                </FILE>
            </TASK>
    </OUTER>
    <OUTER>
                <TYPE>SECOND</TYPE>
                <FIELD1>2</FIELD1>
                <ID>58640</ID>
                <TASK>
                    <FILE>
                        <OPTIONS>1</OPTIONS>
                    </FILE>
                </TASK>
    </OUTER>

The text in the tag ID needs to be updated with a new value, it's present in this variable NEW_ID1.The comparison should happen with the type tag, i.e only if the text == FIRST, we need to replace the ID with new ID, and write it back to XML similarly if type = SECOND, update ID with NEW_ID2 and so on,how to do so? I tried the following way,

tree = ET.parse("sample.xml")
root = tree.getroot()

det = tree.findall(".//OUTER[TYPE='FIRST']")
.
.
ID = NEW_ID1
tree.write("sample.xml")

but not able to manipulate it further

1 Answer 1

1

You are close, except TYPE isn't an attribute, it is a tag/element, so [TYPE='FIRST'] will not work.

Instead what you can do is iterate through all of the OUTER tags/elements, and test to see if they contain a TYPE with the value "FIRST" as text value. Then you can grab the OUTER tags ID decendant, and change it's text value.

For example:

tree = ET.parse("sample.xml")
root = tree.getroot()

for outer in tree.findall(".//OUTER"):
    elem = outer.find(".//FIRST")
    if elem.text == "FIRST":
        id_elem = outer.find(".//ID")
        id_elem.text = "NEWID1"

tree.write("sample.xml")

Note: I am assuming that your xml file doesn't only contain the markup that is in your question. There should only be one root element in an xml file.

4
  • The output came out something like this <TYPE ID = "NEW_ID1" >FIRST</TYPE> instead of updating <ID>tag, can you please tell me how to rectify this?
    – LM10
    Feb 3 at 6:20
  • oh... sorry I misunderstood your question.. I will update
    – Alexander
    Feb 3 at 6:30
  • Actually TYPE isn't a tag. It's an element with a begin tag and an end tag. Using incorrect terminology makes it very hard for people to follow documentation and error messages. Feb 3 at 10:25
  • I would reckon it's both... but I will update it if it will make you happy @MichaelKay
    – Alexander
    Feb 3 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.