xmlns namespace attributed as key value pair in generated json

600 views Asked by At

I have a usecase where I need the xmlns namespace attribute as a key value pair in the generated json from xml . But currently I am not able to do so as the namespace is getting ignored.

xml is

<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
<edmx:Reference Uri="../VOC_Core/$metadata">
    <edmx:Include Namespace="Org.OData.Core.V1" Alias="Core" />
</edmx:Reference>
<edmx:DataServices>
    <Schema Namespace="EPMSample" xmlns="http://docs.oasis-open.org/odata/ns/edm">
    </Schema>
</edmx:DataServices>

generated json

 {  
   "Version":"4.0",
   "Reference":{  
      "Uri":"../VOC_Core/$metadata",
      "Include":{  
         "Namespace":"Org.OData.Core.V1",
         "Alias":"Core"
      }
   },
   "DataServices":{  
      "Schema":{  
         "Namespace":"EPMSample"
      }
   }
}

I using fasterxml jackson for the conversion

XmlMapper xmlMapper = new XmlMapper();
JsonNode node = xmlMapper.readTree(xml.getBytes());
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writeValueAsString(node);

How can I include the xmlns attribute as a key value pair in the json What all configuration do I need to do so , as to retains the xmlns attribute ?

1

There are 1 answers

0
kumesana On

Java XML binding defines no mechanism to preserve namespace binding information from the original XML. Therefore when you need this information you need to step out of using XML binding with Jackson or similar.

Instead you can use a general-purpose XML library such as JDOM 2 and read your XML as a DOM, from which you can extract all relevant information including namespace bindings, and put them in your preferred Java object representation.

Once this is done, you can go back to JSON binding to transform the obtained Java object into JSON.

For simplicity you might prefer a mix: unmarshalling your XML into a Map with jackson as usual, and use JDOM 2 to extract the namespaces and add them to your Map.