我想再向xml文件中添加一个块。基本上在父Tss
下我想创建具有其属性的子Entry
。这是我想要添加到xml文件的内容:
<Entry>
<System string = "rbs005019"/>
<Type string = "SECURE"/>
<User string = "rbs"/>
<Password string = "rbs005019"/>
</Entry>
这是xml文件
<ManagedElement sourceType = "CELLO">
<ManagedElementId string = "rbs005019"/>
<Tss>
<Entry>
<System string = "rbs005019"/>
<Type string = "NORMAL"/>
<User string = "rbs"/>
<Password string = "rbs005019"/>
</Entry>
</Tss>
</ManagedElement>
所以在梳理之后应该看起来像:
<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>
我正在使用python 2.6和lxml.etree
。
答案 0 :(得分:1)
答案 1 :(得分:1)
以下是使用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>
插入符合以下行:
current.find('./Tss').insert(0,want)