0

Python 2 Is it posible to change xml file using python when

<Label name="qotl_type_label" position="910,980" font="headline_light" />

Search by name attribute and then change position?

2
  • Please clarify your question. What I can understand is that you want to change an xml file (how? change what to what?), but only if.. what? Do you need assistance with checking if the a satisfies your requirement or with changing the file, or both? Commented Aug 31, 2016 at 14:14
  • I wanted to change attribute in file Commented Aug 31, 2016 at 19:09

1 Answer 1

1

You can use the built-in xml.etree.ElementTree module to parse the XML, locate the Label element and change the position attribute via .attrib property:

>>> import xml.etree.ElementTree as ET
>>>
>>> s = '<root><Label name="qotl_type_label" position="910,980" font="headline_light" /></root>'
>>>
>>> root = ET.fromstring(s)
>>> label = root.find(".//Label[@name='qotl_type_label']")
>>> label.attrib['position'] = 'new,position'
>>> ET.tostring(root)
'<root><Label font="headline_light" name="qotl_type_label" position="new,position" /></root>'

Note that the order of attributes is not preserved, attributes are unordered by definition.

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to search only by name attribute? This will be messy in my program.
@KubaJanek I've done exactly that in the code sample - see the "find()" call where we check the name attribute value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.