python代码,用于根据父标记属性值在深度处插入xml标记

时间:2013-11-26 05:58:55

标签: python xml parsing

我正在解析以下XML文件

使用xml.etree.ElementTree:

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

如何插入&lt;外&GT; 200℃; /外&GT;元素进入&lt;子内和GT;标签在哪里&lt; stream id =“2”one?

1 个答案:

答案 0 :(得分:0)

使用Python lxml包尝试此操作。 :因为lxml支持xpath在xml上触发查询。

from lxml import etree

tree = etree.parse("C:\\abc.xml")
root = tree.getroot()
elem = tree.xpath("//stream[@id='2']//sub-inner")[0]
elem.append( etree.Element("outer") )
elem1 = tree.xpath("//stream[@id='2']//sub-inner//outer")[0]
elem1.text = "200"

它会在outer sub-inner附加新元素stream id="2"

输出将是:

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