0

I have below json with xml file. I am looking for a solution to extract the xml part and traverse xml attribute using python 'ElementTree' or any other library ..

{
   "Data":{
      "myevent":{
         "payload":"<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>",
         "meta_data":{
            "Env":"l1-7",
            "EventName":"myEventName",
            "Source":"mysource",
            "Hash":"myhash",
            "PayloadKey":"mypayload",
            "ByteSize":300,
            "EventTim":"myTime",
            "Entity":"myEntity",
            "version":"myVersion"
         }
      }
   }
}

Now I want to extract the "payload" value as a XML, so I can traverse it for further transformation using Python ElementTree library.

Appreciated if anybody can help on this.

Thanks

1
  • What is the problem? Have you tried anything at all? Commented Dec 8, 2020 at 6:46

1 Answer 1

1

To extract the payload (the XML), you can just index the data as you normally do in Python for dicts. This will give you a Python string. Then, you can pass it to the fromstring method so that you can traverse it.

Example:

import xml.etree.ElementTree as ET


data = {
   "Data":{
      "myevent":{
         "payload":"<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>",
         "meta_data":{
            "Env":"l1-7",
            "EventName":"myEventName",
            "Source":"mysource",
            "Hash":"myhash",
            "PayloadKey":"mypayload",
            "ByteSize":300,
            "EventTim":"myTime",
            "Entity":"myEntity",
            "version":"myVersion"
         }
      }
   }
}

tree = ET.fromstring(data['Data']['myevent']['payload'])
for element in tree:
    print(element.text)
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.