cptPH
cptPH

Reputation: 2401

I want to add a value to an existing XML object/tree in python

As of now I import an existing XML-tempalte:

from lxml import etree
xmlTemplate = etree.parse('linux_inv.xml')
xml = xmlTemplate.getroot()

XML-template (simplified):

<InventoryData>
<general/>
    <Table Name="InvMain">
        <Column Name="ID">0</Column>
    </Table>
    <Table Name="InvComputer">
        <Column Name="Hostname"></Column>
    </Table>
</InventoryData>

Now I want to add a string value to the table with Name="InvComputer" and the column with Name="Hostname". Something like that:

xml[InventoryData][Table@Name="InvComputer"][Column@Name="Hostname"].text = "jumpServer01"

Sadly I can't find it that way. Only iterating over the whole xml tree and checking every attribute along the way.

I am working with python 2.7.3 and I don't care which xml implementation is used.

Upvotes: 0

Views: 43

Answers (1)

max
max

Reputation: 2817

You can do this using XPath expressions. To get the required node, you may use this code

nodes = xmlTemplate .xpath('/InventoryData/Table[@Name="InvComputer"]/Column[@Name="Hostname"]')

You may also check out this documentation about xpath in lxml and this one about xpath syntax.

Upvotes: 1

Related Questions