Java 使用 DOM4J 解析 XML 并转换为 JSON 示例
以下是使用 Java 处理字符串格式的 XML 信息并将其转化为 JSON 格式的示例代码,示例代码演示如何使用 Java 和 DOM4J 库解析 XML 数据并将其转换为 JSON 格式,并从 XML 中提取特定节点信息,并将信息转化为 JSON 对象。
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.JSONObject;
public class XmlToJsonConverter {
public static void main(String[] args) {
String xml = '<Organization><Department></Department><Devices><Device id="1000028" type="601" name="报警主机"><UnitNodes index="0" channelnum="60" type="3"><Channel id="1000028$3$0$0" name="防区1" desc="" status="0" channelType="0" channelSN="" rights="11000000000000000000000011101000000101100011111111111111111" alarmType="80081" alarmLevel="1" /> </UnitNodes></Device></Devices></Organization>';
try {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
Element deviceElement = root.element('Devices').element('Device');
JSONObject json = convertElementToJson(deviceElement);
System.out.println(json.toString());
} catch (DocumentException e) {
e.printStackTrace();
}
}
private static JSONObject convertElementToJson(Element element) {
JSONObject json = new JSONObject();
json.put('id', element.attributeValue('id'));
json.put('type', element.attributeValue('type'));
json.put('name', element.attributeValue('name'));
JSONObject unitNodesJson = new JSONObject();
Element unitNodesElement = element.element('UnitNodes');
unitNodesJson.put('index', unitNodesElement.attributeValue('index'));
unitNodesJson.put('channelnum', unitNodesElement.attributeValue('channelnum'));
unitNodesJson.put('type', unitNodesElement.attributeValue('type'));
JSONObject channelJson = new JSONObject();
Element channelElement = unitNodesElement.element('Channel');
channelJson.put('id', channelElement.attributeValue('id'));
channelJson.put('name', channelElement.attributeValue('name'));
channelJson.put('desc', channelElement.attributeValue('desc'));
channelJson.put('status', channelElement.attributeValue('status'));
channelJson.put('channelType', channelElement.attributeValue('channelType'));
channelJson.put('channelSN', channelElement.attributeValue('channelSN'));
channelJson.put('rights', channelElement.attributeValue('rights'));
channelJson.put('alarmType', channelElement.attributeValue('alarmType'));
channelJson.put('alarmLevel', channelElement.attributeValue('alarmLevel'));
unitNodesJson.put('channel', channelJson);
json.put('unitNodes', unitNodesJson);
return json;
}
}
输出结果为:
{
"id": "1000028",
"type": "601",
"name": "报警主机",
"unitNodes": {
"index": "0",
"channelnum": "60",
"type": "3",
"channel": {
"id": "1000028$3$0$0",
"name": "防区1",
"desc": "",
"status": "0",
"channelType": "0",
"channelSN": "",
"rights": "11000000000000000000000011101000000101100011111111111111111",
"alarmType": "80081",
"alarmLevel": "1"
}
}
}
原文地址: https://www.cveoy.top/t/topic/fRaW 著作权归作者所有。请勿转载和采集!