Reputation: 173
I want to add one more block to xml file. Basicly under parent Tss
I want to create sublement Entry
with its attributes. Here is what I want to add to xml file:
<Entry>
<System string = "rbs005019"/>
<Type string = "SECURE"/>
<User string = "rbs"/>
<Password string = "rbs005019"/>
</Entry>
and here is the xml file
<ManagedElement sourceType = "CELLO">
<ManagedElementId string = "rbs005019"/>
<Tss>
<Entry>
<System string = "rbs005019"/>
<Type string = "NORMAL"/>
<User string = "rbs"/>
<Password string = "rbs005019"/>
</Entry>
</Tss>
</ManagedElement>
so after combing it should look like:
<ManagedElement sourceType = "CELLO">
<ManagedElementId string = "rbs005019"/>
<Tss>
<Entry>
<System string = "rbs005019"/>
<Type string = "NORMAL"/>
<User string = "rbs"/>
<Password string = "rbs005019"/>
</Entry>
<Entry>
<System string = "rbs005019"/>
<Type string = "SECURE"/>
<User string = "rbs"/>
<Password string = "rbs005019"/>
</Entry>
</Tss>
</ManagedElement>
I'm using python 2.6 and lxml.etree
.
Upvotes: 0
Views: 73
Reputation: 5805
Here is an example of using insert:
In [31]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:current = """ <ManagedElement sourceType = "CELLO">
: <ManagedElementId string = "rbs005019"/>
: <Tss>
: <Entry>
: <System string = "rbs005019"/>
: <Type string = "NORMAL"/>
: <User string = "rbs"/>
: <Password string = "rbs005019"/>
: </Entry>
: </Tss>
: </ManagedElement>
:"""
:<EOF>
In [32]: current = etree.fromstring(current)
In [33]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:want = """
: <Entry>
: <System string = "rbs005019"/>
: <Type string = "SECURE"/>
: <User string = "rbs"/>
: <Password string = "rbs005019"/>
: </Entry>
:"""
:<EOF>
In [34]: want = etree.fromstring(want)
In [35]: current.find('./Tss').insert(0,want)
In [36]: print etree.tostring(current, pretty_print=True)
<ManagedElement sourceType="CELLO">
<ManagedElementId string="rbs005019"/>
<Tss>
<Entry>
<System string="rbs005019"/>
<Type string="SECURE"/>
<User string="rbs"/>
<Password string="rbs005019"/>
</Entry>
<Entry>
<System string="rbs005019"/>
<Type string="NORMAL"/>
<User string="rbs"/>
<Password string="rbs005019"/>
</Entry>
</Tss>
</ManagedElement>
The insert happens with this line:
current.find('./Tss').insert(0,want)
Upvotes: 1