如何使用python解析在XML中的元素上方插入与属性值相同的属性值

时间:2018-07-31 04:20:59

标签: python xml parsing

我一直在使用python通过xml.etree.ElementTree模块来解析和修改XML。

是否可以将相同的属性值插入到下一个相同的级别元素?

下面是XML示例:

<Root>
    <AAA size="small">
        <BBB>1</BBB>
    </AAA>
    <AAA>   <---- this element has no attribute
        <CCC>*</CCC>
    </AAA>
        <BBB>1</BBB>
    <AAA size="big">
        <BBB>1</BBB>
        <CCC>*</CCC>
    </AAA>
    <AAA>   <---- this element has no attribute
        <BBB>1</BBB>  
    </AAA>
    <AAA>   <---- this element has no attribute
        <CCC>1</CCC>  
    </AAA>
</Root>

我想将相同的属性值插入到下一个相同的元素中,如下所示。

<Root>
    <AAA size="small">
        <BBB>1</BBB>
    </AAA>
    <AAA size="small">   <---- insert same attribute following AAA right above
        <CCC>*</CCC>
    </AAA>
        <BBB>1</BBB>
    <AAA size="big">   
        <BBB>1</BBB>
        <CCC>*</CCC>
    </AAA>
    <AAA size="big">   <---- insert same attribute following AAA right
        <BBB>1</BBB>  
    </AAA>
    <AAA size="big">   <---- insert same attribute following AAA right
        <CCC>1</CCC>  
    </AAA>
</Root>

所以,我想知道是否可以使用python做到这一点。

谢谢

1 个答案:

答案 0 :(得分:1)

尝试:

import xml.etree.ElementTree as ET
tree = ET.parse(filename)
root = tree.getroot()

previousAttr = ""
for child in root:
    if child.attrib:
        previousAttr = child.attrib         #Get Previous Attribute.
    else:
        for k,v in previousAttr.items():
            child.set(k, v)                  #Update Attribute.

tree.write(open(filename1, 'wb'))