Python ElementTree如何为XML所有row节点批量添加自定义子元素
为XML所有row节点批量添加自定义FID子元素
需求
为整份XML的所有row节点添加统一的自定义FID数据。
现有XML数据
<?xml version='1.0' encoding='utf-8'?> <data> <row> <index>0</index> <price>$5.95</price> <name>Belgian Waffles</name> <desc>Two of our famous Belgian Waffles with plenty of real maple syrup</desc> <calories>650</calories> </row> <row> <index>1</index> <price>$7.95</price> <name>Strawberry Belgian Waffles</name> <desc>Light Belgian waffles covered with strawberries and whipped cream</desc> <calories>900</calories> </row> <row> <index>2</index> <price>$8.95</price> <name>Berry-Berry Belgian Waffles</name> <desc>Light Belgian waffles covered with an assortment of fresh berries and whipped cream</desc> <calories>900</calories> </row> <row> <index>3</index> <price>$4.50</price> <name>French Toast</name> <desc>Thick slices made from our homemade sourdough bread</desc> <calories>600</calories> </row> <row> <index>4</index> <price>$6.95</price> <name>Homestyle Breakfast</name> <desc>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</desc> <calories>950</calories> </row> </data>
原有编写的处理代码
import xml.etree.ElementTree as ET parse_xml = ET.parse('/content/sample_data/xyz.xml') get_root_element = parse_xml.getroot() ET.SubElement(get_root_element[0],'FID') for data in get_root_element: customtext = 'ABC' data.text = str(customtext) parse_xml.write('abc.xml')
原有代码问题
ET.SubElement(get_root_element[0],'FID')仅选中根节点下索引为0的第一个<row>节点,因此只会给第一个节点添加FID子元素,无法覆盖所有row节点- 循环中直接给row节点的
text属性赋值,会覆盖<row>标签下原有的index、price、name等所有子节点,导致原有数据全部丢失
修正方案
把创建FID子元素的逻辑放到遍历所有row节点的循环内,给FID子元素本身赋值即可,不要修改row节点的text属性,写入文件时补充编码和XML声明参数保证格式正确:
import xml.etree.ElementTree as ET parse_xml = ET.parse('/content/sample_data/xyz.xml') get_root_element = parse_xml.getroot() custom_fid_value = 'ABC' # 遍历根节点下所有row节点 for row in get_root_element: # 为当前row节点创建FID子元素 fid_elem = ET.SubElement(row, 'FID') # 给FID元素设置自定义值 fid_elem.text = custom_fid_value # 写入文件,保留XML声明和utf-8编码 parse_xml.write('abc.xml', encoding='utf-8', xml_declaration=True)
运行效果
处理后每个<row>节点末尾都会新增<FID>ABC</FID>子元素,原有节点的所有内容不会被破坏,输出文件格式和原XML保持一致。
内容的提问来源于stack exchange,提问作者kiric8494
相关产品推荐
相关产品推荐

