用于在xml中添加标记的Python代码,其中父标记是具有不同属性的多个标记

时间:2013-11-25 13:46:42

标签: python xml parsing

我正在使用xml.etree.ElementTree解析以下XML文件:

<main>
    <stream id="1" name="some">
        <inner id="500">
              <sub-inner>
                 <inside> 500 </inside>
              <sub-inner>
        <inner>
    <stream id="2" name="some">
        <inner id="500">
              <sub-inner>
                 <inside> 500 </inside>
              <sub-inner>
        <inner>
    </stream>
</main>

如何将<outer>200</outer>元素插入&lt;子内和GT;标签where stream id =&#34; 2&#34;一个?

1 个答案:

答案 0 :(得分:2)

import xml.etree.ElementTree as ET

root = ET.fromstring('''
<main>
    <stream id="1" name="some">
        <inner>500</inner>
    </stream>
    <stream id="2" name="some">
        <inner>500</inner>
    </stream>
</main>''')
stream = root.find('.//stream[@id="2"]')
outer = ET.SubElement(stream, 'outer')
outer.text = '200'
print(ET.tostring(root))

输出:

<main>
    <stream id="1" name="some">
        <inner>500</inner>
    </stream>
    <stream id="2" name="some">
        <inner>500</inner>
    <outer>200</outer></stream>
</main>

如果您希望outer出现在inner

之前
...
stream = root.find('.//stream[@id="2"]')
outer = ET.Element('outer')
outer.text = '200'
stream.insert(0, outer)
print(ET.tostring(root))

输出:

<main>
    <stream id="1" name="some">
        <inner>500</inner>
    </stream>
    <stream id="2" name="some">
        <outer>200</outer><inner>500</inner>
    </stream>
</main>