我有一个格式如下的文件
<reports>
<report>
<text>....</text>
<author>...</author>
</report>
<report>
<text>....</text>
<author>...</author>
</report>
</reports>
报告根节点包含多个report
个节点。我想将所有单个报告节点转换为json对象(我将保存为单个文件)。
我是XML新手并尝试使用以下代码
List<String> readLines = IOUtils.readLines(new FileInputStream(new File("file.xml")));
String out = String.join("\n", readLines);
//convert to XML
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(out)));
if (doc != null) {
XPathExpression expression = XPathFactory.newInstance().newXPath().compile("/reports");
Node reportsRoot = (Node) expression.evaluate(doc, XPathConstants.NODE);
NodeList reports = reportsRoot.getChildNodes();
for (int i = 0; i < reports.getLength(); i++) {
//I am stuck here. How can I convert the report node into a json object?
}
}
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:0)
我无法弄清楚如何提取XML子节点并将它们转换为JSON。所以我将整个XML文件转换为JSON,然后提取单个报告。那更容易。这是我使用的代码:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.XML;
public class Main {
public static void main(String[] args) {
try {
List<String> readLines = IOUtils.readLines(new FileInputStream(new File("test.xml")));
String out = String.join("\n", readLines);
JSONObject jsonObj = XML.toJSONObject(out);
JSONObject reportsObj = (JSONObject) jsonObj.get("reports");
JSONArray reports = (JSONArray) reportsObj.get("report");
int reportCount = reports.length();
for (int i = 0; i < reportCount; i++) {
JSONObject report = (JSONObject) reports.get(i);
System.out.println(report);
}
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}