1

I have a requirement for dynamically creating a XML, with given input parameters like XSD file and JSON string (if required JSON message can be converted HashMap object). Java program should associate element name present in JSON string/HashMap object with the element name present in XSD and generate XML accordingly. Also please note that, I will have multiple XSDs out of which one will be passed in as input to the program based on some condition.

Input Data:

1) JSON String:
---------------
    {
        "employeeInput":{
            "name":"someone",
            "age":"25",
            "street":"high street",
            "city":"Amsterdam"
        }
    }

    (or I can convert JSON string to HashMap object and send this object as input)

HashMap Object: 
---------------
    {employeeInput={name=someone, age=25, street=high street, city=Amsterdam}}

2) XSD File:
------------
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
         xmlns="http://www.XYZOrganization.com/schemas/Request_Handler/Schema.xsd"
         targetNamespace="http://www.XYZOrganization.com/schemas/Request_Handler/Schema.xsd"
         elementFormDefault="qualified"
         attributeFormDefault="unqualified">
        <xs:element name="employeeInput">
            <xs:complexType>
                <xs:sequence>
                    <xs:element ref="name"/>
                    <xs:element ref="age"/>
                    <xs:element ref="street"/>
                    <xs:element ref="city"/>
                </xs:sequence>
            </xs:complexType>
        </xs:element>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="age" type="xs:string"/>
        <xs:element name="street" type="xs:string"/>
        <xs:element name="city" type="xs:string"/>
    </xs:schema>

Expected Output XML (with namespace and prefix according to XSD):

    <?xml version="1.0" encoding="UTF-8"?>
    <ns0:employeeInput xmlns:ns0="http://www.XYZOrganization.com/schemas/Request_Handler/Schema.xsd">
        <ns0:name>someone</ns0:name>
        <ns0:age>25</ns0:age>
        <ns0:street>high street</ns0:street>
        <ns0:city>Amsterdam</ns0:city>
    </ns0:employeeInput>

Kindly let me know if there is any option available to achieve this. I have read about JAXB marshalling, but have very little idea how to implement this.

Thanks,

Param

3 Answers 3

0

1. Parse Json String into Map using Gson, download it from here

  JsonParser jsonParser = new JsonParser();
    JsonElement element = jsonParser.parse(Your_JSON_STRING_GOES_HERE).getAsJsonObject().get("employeeInput");
    Type typeOf = new TypeToken<Map<String, String>>(){}.getType();
    Map<String, String> map =gson.fromJson(element, typeOf);

2. for marshaling you need do these step

package-info.java

@XmlSchema(
        namespace = "http://www.XYZOrganization.com/schemas/Request_Handler/Schema.xsd",
        elementFormDefault = XmlNsForm.QUALIFIED,
         xmlns={@XmlNs(prefix="ns0", namespaceURI="http://www.XYZOrganization.com/schemas/Request_Handler/Schema.xsd")}
        ) 

package test;

import javax.xml.bind.annotation.*;

create Pojo class.

@XmlRootElement(name="employeeInput")
public class Foo {

    private String name;
    private String age;
    private String street;
    private String city;
//setter/getter
}

Populate jaxb model class from map

// populate jaxb model class
        Foo foo = new Foo();
        foo.setAge(map.get("age"));
        foo.setCity(map.get("city"));
        foo.setName(map.get("name"));
        foo.setStreet(map.get("street"));

// finally Marshall it

Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(foo, System.out);
Sign up to request clarification or add additional context in comments.

Comments

0

Handling JSON is too simple...

So, First Go with your XSD.

Use XJC tool to produce Java Classes(JAXB POJO's). You can find a quick tutorial for that here.

xjc schema.xsd 

Where schema is your xsd.

Then Populate the classes with your json.

Use a json library to parse the json object like simplejson, org.json or Gson

In my case I would use org.json.

Kindly add the json library to your class path, then

JSONObject json = new JSONObject("YourJsonStringGoesHere");

then set the Fields of your POJO's with this json object.

like...

JSONObject MyJson=JSONObject.get("employeeInput"); //gets root object

EmployeeInput obj = new EmployeeInput(); //Instantiate your pojo class

//Let's start populating your pojo

obj.setName(MyJson.getString("name"));
obj.setAge(MyJson.getInt("age"));

//after populating your pojo 
//marshal the pojo with JAXB to create your xml

try {
            JAXBContext context = JAXBContext.newInstance(EmployeeInput.class);
            Marshaller m = context.createMarshaller();
            //for pretty-print XML in JAXB
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            // Write to System.out for debugging
            // m.marshal(emp, System.out);

            // Write to File
            m.marshal(emp, new File(FILE_NAME));
    } 
catch (JAXBException e) 
     {
                e.printStackTrace();
     }

Comments

0

Underscore-java library has static method U.jsonToXml(json). I am the maintainer of the project.

Output xml:

<?xml version="1.0" encoding="UTF-8"?>
<employeeInput>
  <name>someone</name>
  <age>25</age>
  <street>high street</street>
  <city>Amsterdam</city>
</employeeInput>

Comments

Your Answer

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