【问题标题】:convert xpath expression result to json将 xpath 表达式结果转换为 json
【发布时间】:2015-02-15 20:45:15
【问题描述】:

我想将一个 dom 节点列表转换为一个 json 数组并将结果发送给一个 REST 客户端:

xml的每个节点代表如下:

<A NAME="x" COUNT="y">
  <B KEY="z1" VALUE="z2"/>
  <B KEY="z3" VALUE="z4"/>
</A>

我希望输出一个对象数组,其中每个对象如下所示:

{"NAME":"x", 
 "COUNT":"y", 
 "B": [ {"KEY": "z1,  VALUE:"z2"},
        {"KEY":"z3", VALUE:"z4"} ]
}

我尝试使用 GSON 库:

package com.a;


import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class Test {
    private static final String XPATH = "/A/B";
    
    public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        File f = new File("C:/Users/abc/Desktop/a.xml");
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = null;
        builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(f);
        XPath xPath =  XPathFactory.newInstance().newXPath();
        
        NodeList nodeList = (NodeList) xPath.compile(XPATH).evaluate(xmlDocument, XPathConstants.NODESET);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        
        String jsonOutput = gson.toJson(nodeList);
        System.out.println(jsonOutput);
        
        
        
        
    }

}

但我遇到了错误

线程“主”java.lang.StackOverflowError 中的异常

java.lang.StringBuffer.append(StringBuffer.java:224) 在

java.io.StringWriter.write(StringWriter.java:84) 在

com.google.gson.stream.JsonWriter.newline(JsonWriter.java:569) 在

com.google.gson.stream.JsonWriter.beforeName(JsonWriter.java:586)

如何修复此代码?

因为可以将整个 xml 转换为 json (Quickest way to convert XML to JSON in Java)

我假设可以将 dom 节点转换为 json。这里有什么问题?

【问题讨论】:

    标签: java xml json


    【解决方案1】:

    怎么了?您根本不使用链接中描述的库 (Quickest way to convert XML to JSON in Java)

    Gson 将使用 java 反射从任何对象生成一个 json 字符串。从 DOM 文档(或节点)中,即使它没有以 StackOverflowError 结束,它也不会产生您期望的结果。这是您的 XML 的结果:

    {"fNamespacesEnabled":false,"mutationEvents":false,"actualEncoding":"UTF-8","standalone":false,"fDocumentURI":"...a.xml","changes":0,"allowGrammarAccess":false,"errorChecking":true,"ancestorChecking":true,"xmlVersionChanged":false,"documentNumber":0,"nodeCounter":0,"xml11Version":false,"flags":6}
    

    实际上,如果在 DOM 文档(例如:getDocumentElement)上调用了任何方法,gson.toJson 最终会出现 StackOverflowError。

    正如您在链接中看到的,可以在此处找到可以完成这项工作的 jar:http://mvnrepository.com/artifact/org.json/json

    这意味着您将使用 XPath 提取的节点重新转换为字符串。 你可以这样做:

    private static String toString(Node n) throws TransformerFactoryConfigurationError, TransformerException {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(new StringWriter());
        DOMSource source = new DOMSource(n);
        transformer.transform(source, result);
        return result.getWriter().toString();
    }
    

    有了这一切,你所要做的就是遍历你的nodeList,将其转换为字符串,然后将其转换为json

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node n = nodeList.item(i);
        JSONObject xmlJSONObj = XML.toJSONObject(toString(n));
        String jsonPrettyPrintString = xmlJSONObj.toString(1);
        System.out.println(jsonPrettyPrintString);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 2013-09-17
      相关资源
      最近更新 更多