Is there a way to convert a xml file to json? The XML can be of any structure, therefore there is no POJO class for instantiation. I need to convert the xml to json or to a Map, without root nodes.
For example:
<import name="person">
<item>
<firstName>Emil</firstName>
<lastName>Example</lastName>
<addresses>
<address>
<street>Example Blvd.</street>
</address>
<address>
<street>Example Ave.</street>
</address>
</addresses>
</item>
</import>
Expected JSON
{
"firstName": "Emil",
"lastName": "Example",
"addresses": [
{ "street" : "Example Blvd." },
{ "street" : "Example Ave." }
]
}
org.json.XML
If you are using Java 8, you should check out my open source library: unXml. unXml basically maps from Xpaths to Json-attributes.
It's available on Maven Central.
Example
It will return a Jackson
ObjectNode
, with the json from your example.You can Use JSON and XML Library from json.org
Source
Output
You can use standard tools for it
xjc
from your jdk to generate Java classes from schemaSince Java 11 you have to download
xjc
in an extra step from https://javaee.github.io/jaxb-v2/XML
write out asJSON
using JacksonExample
With https://schema.datacite.org/meta/kernel-4.1/metadata.xsd
1. Use the tool
xjc
from your jdkIn my example I will use a fairly complex example based on datacite schemas.
This will reply with
2. Read in as
XML
write out asJSON
using JacksonPrints:
For example input XML :
On this website you find some helpful classes for your task.
Underscore-java library has static method
U.xmlToJson(xml)
. I am the maintainer of the project. Live example