Reputation: 2401
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
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