1

I'm really newbie in python. I need to write some string in existing xml file.

My XML strutcure is like this:

    <koza>
      <colors>
        <color name="one" **value="#00FF00"** />
        <color name="two" value="#a12345" />
        <color name="three" value="#c2c145" />
        <color name="four" value="#315a25" />
        ...
      </colors>
    </koza>

I only need to change value in one line, example, in first line change "#00FF00" to "#FFFFFF".

Is there a simple code to do this?

Thanks!

1
  • By the way, how exactly you define the "first line" matters. Do you identify it because it's the color named "one"? Because it's the color with the original value #00FF00? The first child of the <colors> element? Something else? Commented Feb 25, 2014 at 18:30

1 Answer 1

2
import lxml.etree

# input
doc = lxml.etree.parse('input_file.xml'))

# modification
for el in doc.xpath("//color[@name='one']"):
  el.attrib['value'] = '#FFFFFFFF'

# output
open('output_file.xml', 'w').write(lxml.etree.tostring(doc))
Sign up to request clarification or add additional context in comments.

1 Comment

For me doc.write ('FILEPATH') (stackoverflow.com/questions/47439566/…) is shorter and working.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.