-4

I want to convert xml to json as per below example: Sample XML:

    <Details>
         <Records>
           <name id='123'>xyz</name>
           <age>25</age>
           <gender type='male' />
          </Records>
    </Details>

Expected JSON Output:

{
  "Details": {
    "Records": {
      "name": {
        "@id": "123",
        "#text": "xyz"
      },
      "age": "25",
      "gender": { 
        "@type": "male" 
       }
    }
  }
}

Please help me.

  • 1
    What have you tried? What tool/library do you want to use? Your question is too unspecific right now -- there a tons of ways to do this. – Matthias J. Sax Sep 24 '15 at 13:21
  • Please follow below url, [Convert XMl to JsonObject using Javascript,Jquery][1] [1]: http://stackoverflow.com/questions/20679135/convert-xml-to-jsonobject-using-javascript-jquery – Sanjay Bhardwaj Sep 24 '15 at 13:23
  • No. I need to build it from scratch. No code with me. Need to know the approach for doing this. – Shayan Singla Sep 24 '15 at 13:25
  • Please follow this link [Convert XMl to JsonObject using Javascript,Jquery][1] [1]: http://stackoverflow.com/questions/20679135/convert-xml-to-jsonobject-using-javascript-jquery – Sanjay Bhardwaj Sep 24 '15 at 13:26

2 Answers2

0

Create a class representation of the data. Then use an object mapper like Jackson that understands JSON and XML. Deserialize from XML and serialize into JSON.

sh0rug0ru
  • 1,596
  • 9
  • 9
  • I need to make it a generic function that can handle any schema. – Shayan Singla Sep 24 '15 at 13:24
  • Jackson is a generic mapping tool. But you need to define a class to serve as a common data model between XML and JSON that describes the shape of the output that you want. That class can be as generic as Map, but you will not be able to get as specific results as you are asking for without a proper definition. – sh0rug0ru Sep 24 '15 at 13:31
0

If you are using Java 8, you should have a look at my unXml-library. It's open source and available on Maven Central.

This code would work for your project

import com.nerdforge.unxml.Parsing;
import com.nerdforge.unxml.factory.ParsingFactory;
import org.w3c.dom.Document;
import java.util.List;

public class Parser {
    public ObjectNode parseXml(String xml){
        Parsing parsing = ParsingFactory.getInstance().create();
        Document document = parsing.xml().document(xml);

        Parser<ObjectNode> parser = parsing.obj("Details")
            .attribute("Records", parsing.obj("Records")
                .attribute("name", parsing.obj("name")
                    .attribute("@id", "@id")
                    .attribute("#text", "text()")
                )
                .attribute("age", "age")
                .attribute("gender", parsing.obj("gender")
                    .attribute("@type", "@type")
                )
            )
            .build();

        ObjectNode result = parser.apply(document);
        return result;
    }
}

Note that the whole point with this library, is to extract values from XMLs using Xpaths, and assigning them to attributes in Json Objects. So you can create "nicer" Json, that's not so bound to the xml structure.

Example

public class Parser {
    public ArrayNode parseXml(String xml){
        Parsing parsing = ParsingFactory.getInstance().create();
        Document document = parsing.xml().document(xml);

        Parser<ArrayNode> parser = parsing.arr("//Records", parsing.obj()
            .attribute("id", "name/@id", parsing.number())
            .attribute("name") // name is both the xpath, and json-attribute key
            .attribute("age", "age", parsing.number())
            .attribute("gender", "gender/@type")
        ).build();

        ArrayNode result = parser.apply(document);
        return result;
    }
}

Will return the json

[{
    id: 123,
    name: "xyz",
    age: 25,
    gender: "male" 
}]

Use parsing.arr("<xpath>", ...) to create arrays.

tomaj
  • 1,570
  • 1
  • 18
  • 32
  • 1
    This will work only if i know the xml structure coming to me. But the XML tags can vary. – Shayan Singla Sep 27 '15 at 05:19
  • @ShayanSingla That is correct. You would have to know your xml-structure in advance to be able to use `unXml`. – tomaj Sep 27 '15 at 07:13
  • @ShayanSingla My use cases often involve using the Json in a JS-based web application later. And it is considered good practice to simplify your model as much as possible server side, so that the client-side JavaScript can be as simple as possible. The JS-code will also (usually) expect a well-defined object (or array of objects). – tomaj Sep 27 '15 at 07:16