无需使用第三方库即可将xml字符串转换为JSON字符串 [英] Convert xml string to JSON string without using third party libs

查看:235
本文介绍了无需使用第三方库即可将xml字符串转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些xml格式的字符串,需要将其转换为JSON格式.我已阅读在Java中将XML转换为JSON的最快方法,但是除了标准Java外,我们不能使用任何外部库.

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?

这是xml字符串,如下所示:

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>

需要将其更改为:

{

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

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

}

推荐答案

您可以从XSL转换的角度看这个问题.因此,您可以使用 JAXP Java SE SDK(没有其他依赖项).

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());

您已经拥有了XML,现在所需的就是XSL代码. 当我发现此网站已经做到这一点时,我正要从头开始写信给您.对我/你. 此处是指向XSL文件的直接链接,制成.

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's a direct link to the XSL file that they made.

注意:这是单向转换.您不能使用它将JSON转换回XML.

享受.

这篇关于无需使用第三方库即可将xml字符串转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆