Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert XML to JSON format

Tags:

java

json

xml

docx

I have to convert docx file format (which is in openXML format) into JSON format. I need some guidelines to do it. Thanks in advance.

like image 519
vignesh Avatar asked Feb 25 '11 04:02

vignesh


People also ask

Can we convert XML to JSON in Postman?

Parse the XML to JSON using var jsonObject = xml2Json(responseBody); With Json Object You can parse as normal json.

Can we convert XML to JSON in Java?

Most of the applications use this format for transmitting the data from the server to the web page, or vice-versa. However, we can use the org. json. XML class in Java to convert the XML to JSON.


2 Answers

You may take a look at the Json-lib Java library, that provides XML-to-JSON conversion.

String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
XMLSerializer xmlSerializer = new XMLSerializer();  
JSON json = xmlSerializer.read( xml );  

If you need the root tag too, simply add an outer dummy tag:

String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
XMLSerializer xmlSerializer = new XMLSerializer();  
JSON json = xmlSerializer.read("<x>" + xml + "</x>");  
like image 90
Tommy Siu Avatar answered Oct 20 '22 21:10

Tommy Siu


There is no direct mapping between XML and JSON; XML carries with it type information (each element has a name) as well as namespacing. Therefore, unless each JSON object has type information embedded, the conversion is going to be lossy.

But that doesn't necessarily matter. What does matter is that the consumer of the JSON knows the data contract. For example, given this XML:

<books>
  <book author="Jimbo Jones" title="Bar Baz">
    <summary>Foo</summary>
  </book>
  <book title="Don't Care" author="Fake Person">
    <summary>Dummy Data</summary>
  </book>
</books>

You could convert it to this:

{
    "books": [
        { "author": "Jimbo Jones", "title": "Bar Baz", "summary": "Foo" },
        { "author": "Fake Person", "title": "Don't Care", "summary": "Dummy Data" },
    ]
}

And the consumer wouldn't need to know that each object in the books collection was a book object.

Edit:

If you have an XML Schema for the XML and are using .NET, you can generate classes from the schema using xsd.exe. Then, you could parse the source XML into objects of these classes, then use a DataContractJsonSerializer to serialize the classes as JSON.

If you don't have a schema, it will be hard getting around manually defining your JSON format yourself.

like image 31
Jacob Avatar answered Oct 20 '22 21:10

Jacob