简体   繁体   中英

Convert xml string to JSON string without using third party libs

I have some string in xml format and need to convert it into JSON format. I have read Quickest way to convert XML to JSON in Java but we can't use any external libs but standard Java.

Is there any simple or good way to achieve this without any third party libs?

Here is the xml string looks like:

<container>
     <someString>xxx</someString>     
     <someInteger>123</someInteger>     
     <someArrayElem>         
        <key>1111</key>         
        <value>One</value>     
    </someArrayElem>     

    <someArrayElem>         
    <key>2222</key>         
    <value>Two</value>     
    </someArrayElem> 
</container>

Need change it into:

{

   "someString": "xxx",   
   "someInteger": "123",
   "someArrayElem": [
      {
         "key": "1111",
         "value": "One"
      },

      {
         "key": "2222",
         "value": "Two"
      }
   ]

}

You could look at this problem, from the point of view of XSL transformations. So, you could use JAXP , which is included in the Java SE SDK (no additional dependencies).

  // raw xml
  String rawXml= ... ;

  // raw Xsl
  String rawXslt= ... ;

  // create a transformer
  Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer(
     new StreamSource(new StringReader(rawXslt))
  );

  // perform transformation
  StringWriter result = new StringWriter();
  xmlTransformer.transform(
     new StreamSource(new StringReader(rawXml)), new StreamResult(result)
  );

  // print output
  System.out.println(result.getBuffer().toString());

You already have your XML, all what you need now, is your XSL code. I was about to write you one from scratch, when I found out that this website already did it for me/you. Here 'sa direct link to the XSL file that they made.

Note: this is a one-way conversion. You cannot use it to convert JSON back to XML.

Enjoy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM