首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用python脚本更新XML

使用python脚本更新XML
EN

Stack Overflow用户
提问于 2018-09-05 22:09:13
回答 1查看 44关注 0票数 1

我们有一个很大的订单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在所有<custom-attribute>元素上添加如下所示的<value>标记:

当前XML:

代码语言:javascript
运行
复制
<custom-attributes>
       <custom-attribute attribute-id="color">BLACK</custom-attribute>
       <custom-attribute attribute-id="colorDesc">BLACK</custom-attribute>            
</custom-attributes>

转换后的XML:

代码语言:javascript
运行
复制
<custom-attributes>
           <custom-attribute attribute-id="color">
            <value>BLACK</value>
            </custom-attribute>
           <custom-attribute attribute-id="colorDesc">
           <value>BLACK</value>
          </custom-attribute>            
    </custom-attributes>

谢谢

EN

回答 1

Stack Overflow用户

发布于 2018-09-05 22:25:12

您可以解析XML并将SubElement添加到XML。假设您在名为“SomeData.xml”的文件中有XML数据:

代码语言:javascript
运行
复制
<custom-attributes>
       <custom-attribute attribute-id="color">BLACK</custom-attribute>
       <custom-attribute attribute-id="colorDesc">BLACK</custom-attribute>            
</custom-attributes>

您可以使用下一个Python脚本转换此文件:

代码语言:javascript
运行
复制
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":

代码语言:javascript
运行
复制
<custom-attributes>
       <custom-attribute attribute-id="color"><value>BLACK</value></custom-attribute>
       <custom-attribute attribute-id="colorDesc"><value>BLACK</value></custom-attribute>            
</custom-attributes>

希望它能帮上忙!

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52187199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档