问题导航到具有相同名称的xml元素,更改不同的属性

时间:2018-04-03 07:43:27

标签: python xml

如果有一个xml文件,如下所示:

<?xml version="1.0"?>

-<apple view_filter="simple" version="1" format="1">
 <apples fruit_id="3" type="red" name="american">
  <basket version="1" type="6" pieces="12" expiration="12">
  <fruit_type colour="000" fruit_type="0x" weight="32">
  </basket>
 </apples>
</apple>

对于元素 fruit_type =“0x”,我希望能够使用python代码导航到该元素并更改其属性的文本(0x)。我也想为'颜色'和'重量'做同样的事情。

我怎么能这样做,因为当我尝试导航到fruit_type时,我最终改变了fruit_type(第一个元素)而不是那个是fruit_type ='0x'的那个?

2 个答案:

答案 0 :(得分:0)

以下是如何更改Fruit_type属性的示例代码:

示例代码

import xml.etree.ElementTree as ET


parent = ET.parse("d:\\untitled\\note.xml")
root = parent.getroot()

for nodes in root.getchildren() :
    for subNodes in nodes.getchildren() :
        for mynode in subNodes.getchildren():
            print("##### Before Change of attributes ########### \n")
            print(ET.tostring(mynode))
            print("\n ##### After Change of attributes ###########\n")
            mynode.set('fruit_type', '0234')
            mynode.set('colour', '999')
            mynode.set('weight', '45')
            print(ET.tostring(mynode))

<强>输出

##### Before Change of attributes ########### 

b'<fruit_type colour="000" fruit_type="0x" weight="32">\n            </fruit_type>\n        '

 ##### After Change of attributes ###########

b'<fruit_type colour="999" fruit_type="0234" weight="45">\n            </fruit_type>\n        '

希望这会有所帮助

答案 1 :(得分:0)

完全符合我要求的代码是:

 import xml.etree.ElementTree as ET


 parent = ET.parse("d:\\untitled\\note.xml")
 root = parent.getroot()

 for nodes in root.getchildren() :
  for subNodes in nodes.getchildren() :
    for mynode in subNodes.iterfind('basket'):
        print("##### Before Change of attributes ########### \n")
        print(ET.tostring(mynode))
        print("\n ##### After Change of attributes ###########\n")
        mynode.set('fruit_type', '0234')
        mynode.set('colour', '999')
        mynode.set('weight', '45')
        print(ET.tostring(mynode))