Skip to content Skip to sidebar Skip to footer

How To Add An Attribute To A Tag Found Using Xpath In Lxml In Python?

I have the following xml - I want to add multiple xlink attributes to it and make it -

Solution 1:

This is a working example:

from lxml import etree as et

xml = et.parse("your.xml")
root = xml.getroot()
d = root.nsmap

for node in root.xpath("//draw:image", namespaces=d):
    node.attrib["{http://www.w3.org/1999/xlink}href"] = "value"
    node.attrib["{http://www.w3.org/1999/xlink}show"] = "embed"print(et.tostring(xml))

Which for:

<?xml version="1.0" encoding="utf-8"?>
<office:document xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/"xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0"xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0">
<draw:image></draw:image>

Outputs:

<office:documentxmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"xmlns:style="urn:oasis:names:tc:opendocument:xmlns:style:1.0"xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0"xmlns:draw="urn:oasis:names:tc:opendocument:xmlns:drawing:1.0"xmlns:fo="urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0"xmlns:xlink="http://www.w3.org/1999/xlink"xmlns:dc="http://purl.org/dc/elements/1.1/"xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0"xmlns:number="urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0"xmlns:svg="urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0"xmlns:chart="urn:oasis:names:tc:opendocument:xmlns:chart:1.0"xmlns:dr3d="urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0">
<draw:imagexlink:href="value"xlink:show="embed"/>


</office:document>

Or using set:

for node in root.xpath("//draw:image", namespaces=d):
    node.set("{http://www.w3.org/1999/xlink}href", "image")
    node.set("{http://www.w3.org/1999/xlink}show", "embed")

Post a Comment for "How To Add An Attribute To A Tag Found Using Xpath In Lxml In Python?"