我正在使用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;一个?
答案 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>