gpt4 book ai didi

Java8 - 将非常大的 XML 输入转换为 JSON(带有额外的属性)

转载 作者:行者123 更新时间:2023-12-02 06:16:05 25 4
gpt4 key购买 nike

我想将一个巨大的 XML 转换为 JSON。每次识别特定的 XML 标签时,我想将标签的 XML 部分转换为 JSON 并且 我想为其添加一个简单的计数器。

重要的是,输入的 XML 非常大,因此不可能将其放入内存 JSON 树中。

所以... <xml><car>...</car><car>...</car>...

转换为

{"number":2,"car":{"name":"car1"}}
{"number":3,"car":{"name":"car2"}}

最佳答案

感谢 Andreas,我终于找到了处理巨大 XML 文件并将匹配的 xml 元素转换为 JSON 的解决方案。

String testCars = "<root><car><name>car1</name></car><other><something>Unknown</something></other><car><name>car2</name></car></root>";
String startElement = "car";
int volgnummer = 1;
XMLInputFactory factory = XMLInputFactory.newInstance();
try {
XMLStreamReader streamReader = factory.createXMLStreamReader(new StringReader(testCars));
streamReader.nextTag();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("omit-xml-declaration", "yes");
streamReader.nextTag();
while ( streamReader.isStartElement() ||
( ! streamReader.hasNext() &&
streamReader.nextTag() == XMLStreamConstants.START_ELEMENT)) {
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
t.transform(new StAXSource(streamReader), result);
JSONObject jsonObject = XML.toJSONObject(writer.toString());
jsonObject.put("sequence", ++volgnummer);
System.out.println("XmlChunkToJson: " + jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
}

XML 输入:

<?xml version="1.0"?>
<root>
<car>
<name>car1</name>
</car>
<other>
<something>Unknown</something>
</other>
<car>
<name>car2</name>
</car>
</root>

输出 JSON:

XmlChunkToJson: {"sequence":2,"car":{"name":"car1"}}
XmlChunkToJson: {"sequence":3,"other":{"something":"Unknown"}}
XmlChunkToJson: {"sequence":4,"car":{"name":"car2"}}

关于Java8 - 将非常大的 XML 输入转换为 JSON(带有额外的属性),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55871321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com