python - 使用 python 脚本更新 XML

标签 python xml python-3.x

我们有一个很大的订单 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 之前,我们有什么办法添加 <value>全部标记<custom-attribute>使用 python 的元素如下所示:

当前 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 并向 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>

希望对你有帮助!

关于python - 使用 python 脚本更新 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52187199/

相关文章:

android - 将此 Android 布局居中?

xml - Spring Beans 应用程序上下文上的 XPath 查询

python-3.x - 数据分析 - 如何计算空值、NaN 和空字符串值?

python - 通过 pipenv 自定义模块搜索路径(PYTHONPATH)

python - Django 有足够的脚手架吗? (à la Ruby on Rails)

Python,使用正则表达式在文件中搜索html标签

python - reshape 数据帧/旋转数据帧的一部分

python - super 和 __new__ 混淆

java - 如何使用 Jackson 将 POJO 转换为 XML

python-3.x - 如何使用带有要价和出价的 pandas 数据框计算成交量加权平均价格 (VWAP)?