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!

user3348593
  • 13
  • 1
  • 4
  • 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 `` element? Something else? – Charles Duffy Feb 25 '14 at 18:30

1 Answers1

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))
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • 1
    For me `doc.write ('FILEPATH')` (https://stackoverflow.com/questions/47439566/how-to-find-read-and-replace-a-value-in-xml-file-with-python) is shorter and working. – dh81 Feb 06 '20 at 11:02