将父级附加到xml

时间:2015-05-19 15:40:22

标签: python lxml elementtree

我想再向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

2 个答案:

答案 0 :(得分:1)

lxml具有函数parentElem.insert(position, new_element),允许您在其父元素下插入新的子元素。您可以找到示例herehere(部分元素是列表

答案 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)