python - 使用 python 脚本更新 XML
问题描述
我们有一个用于订单的大 XML,我们必须解析它。一些订单属性以<custom-attribute attribute-id="attibute-id">some value</custom-attribute>
. 我们正在通过 SSIS 解析此 XML,并且在检索这些属性的值时遇到问题。我们注意到,如果我们添加一个值,它会起作用<custom-attribute attribute-id="attibute-id"><value>some value</value></custom-attribute>
那么,在使用 SSIS 解析 XML 之前,有什么方法可以使用 python<value>
在所有元素上添加标签,<custom-attribute>
如下所示:
当前的 XML:
<custom-attributes>
<custom-attribute attribute-id="color">BLACK</custom-attribute>
<custom-attribute attribute-id="colorDesc">BLACK</custom-attribute>
</custom-attributes>
转换后的 XML:
<custom-attributes>
<custom-attribute attribute-id="color">
<value>BLACK</value>
</custom-attribute>
<custom-attribute attribute-id="colorDesc">
<value>BLACK</value>
</custom-attribute>
</custom-attributes>
谢谢
解决方案
您可以解析 XML 并将 SubElement 添加到 XML。假设您在名为“SomeData.xml”的文件中有 XML 数据:
<custom-attributes>
<custom-attribute attribute-id="color">BLACK</custom-attribute>
<custom-attribute attribute-id="colorDesc">BLACK</custom-attribute>
</custom-attributes>
您可以使用下一个 Python 脚本转换此文件:
import xml.etree.cElementTree as ET
XML = ET.parse('SomeData.xml').getroot()
for Atr in XML.findall('custom-attribute'): # Foreach 'custom-attribute' in root
Val = ET.SubElement(Atr, "value") # Create new XML SubElement named 'value'
Val.text = Atr.text # Write text from parent to child element
Atr.text = "" # Clear parent text
ET.ElementTree(XML).write("Output.xml")
生成所需的 XML 并将其保存为“Output.xml”:
<custom-attributes>
<custom-attribute attribute-id="color"><value>BLACK</value></custom-attribute>
<custom-attribute attribute-id="colorDesc"><value>BLACK</value></custom-attribute>
</custom-attributes>
希望能帮助到你!
推荐阅读
- reactjs - 如何防止 Office UI Fabric React PeoplePicker 结果在滚动时消失
- python - 在张量流中使用单个 GPU over IP 的简单方法
- python - TensorBoard 显示验证丢失,但未训练
- r - for 循环中的多个 GLM
- c# - 如何在 SQL Server Management Studio 中拦截执行
- netsuite - NetSuite SuiteTalk API 请求限制
- object-detection - 如何使用 yolo3 和 RTMP?
- android - 有没有办法使用颤振在 Spotify 应用程序上链接 Spotify 播放列表?
- android - Android 应用在通话后将变量设置为默认值
- google-apps-script - 如何在谷歌表格中输入或输入数据后锁定或保护行