Python 导航到同名xml元素、更改不同属性时出现问题
如果您有一个如下所示的xml文件:Python 导航到同名xml元素、更改不同属性时出现问题,python,xml,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 colou
<?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\u type=“0x”,我希望能够使用python代码导航到该元素并更改其属性的文本(0x)。我还想对“颜色”和“重量”做同样的处理
我如何才能做到这一点,因为当我尝试导航到fruit\u类型时,我最终更改了fruit\u类型(第一个元素),而不是fruit\u类型='0x'?以下是如何更改fruit\u类型属性的示例代码: 示例代码
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 '
属性更改前
b'\n\n'
#####属性改变后###########
b'\n\n'
希望这有帮助我想要的代码是:
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))
您好,实际上我正在读取一个xml文件,您的代码给了我一个错误。我假设它是ET.fromstring函数?如何将此代码用于xml文件而不是字符串?您好,它正在更改所需元素的值。但是,它实际上也在创建3个元素,这些元素在xml行之后每隔一个子元素中修改一次,因为文档在“basket”之后实际上有更多子元素。希望你能理解这个问题。更新:我已经修复了使用命令:for mynode in subnode的问题。iterfind('basket')我可以理解它总是在更改固定标记的属性,只是使用了你建议的iterfind方法。工作得很好!我的xml文件中有相同的命名属性,常规的find方法只查找第一个。