1

We have a big XML for order and we have to parse it. Some of the order attributes coming as <custom-attribute attribute-id="attibute-id">some value</custom-attribute>. We are parsing this XML through SSIS and it's having issue retrieving value of these attributes. We noticed that if we add a value, it works <custom-attribute attribute-id="attibute-id"><value>some value</value></custom-attribute>

So, before parsing the XML using SSIS, is there any way we add <value> tag on all <custom-attribute> elements as shown below using python:

Current XML:

<custom-attributes>
       <custom-attribute attribute-id="color">BLACK</custom-attribute>
       <custom-attribute attribute-id="colorDesc">BLACK</custom-attribute>            
</custom-attributes>

Transformed 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>

Thanks

1 Answer 1

1

You can parse XML and add SubElement to XML. Let's say that you have XML data in file named "SomeData.xml":

<custom-attributes>
       <custom-attribute attribute-id="color">BLACK</custom-attribute>
       <custom-attribute attribute-id="colorDesc">BLACK</custom-attribute>            
</custom-attributes>

You can convert this file with next Python script:

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")

Which generates desired XML and it saves it as "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>

Hope it helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.