将父项附加到 xml

Append parent to xml

我想在 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

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

下面是一个使用插入的例子:

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)