Next / Previous / Contents / TCC Help System / NM Tech homepage

6. Modifying an existing XML document

If your program needs to read in an XML document, modify it, and write it back out, this operation is straightforward with lxml.

  1. Start by reading the document using the techniques from Section 3, “Reading an XML document”.

  2. Modify the document tree by adding, deleting, or replacing elements, attributes, text, and other features.

    For example, suppose your program has a variable linkNode that contains an Element instance representing an HTML “a” (hyperlink) element, and you want to change the value of its href attribute to point to a different URL, such as This code would do it:

    linkNode.attrib['href'] = ''
  3. Finally, write the document back out to a file as described in Section 5, “Creating a new XML document”.