Java 解析 XML 字符串并提取 Channel 标签数据为 JSON 格式
以下是使用 Java 处理字符串格式的 XML 信息并将 Channel 标签中的数据转化为 JSON 格式的示例代码:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.json.JSONArray;
import org.json.JSONObject;
public class XmlToJsonConverter {
public static void main(String[] args) {
String xml = '<Organization><Department></Department><Devices><Device></Device><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 {
// Parse XML string into a Document object
Document document = new SAXReader().read(xml);
// Get the last Device element
Element deviceElement = (Element) document.selectSingleNode("//Device[last()]");
// Get the UnitNodes element within the Device element
Element unitNodesElement = deviceElement.element("UnitNodes");
// Get all Channel elements within the UnitNodes element
JSONArray channelsArray = new JSONArray();
for (Element channelElement : unitNodesElement.elements("Channel")) {
JSONObject channelJson = new JSONObject();
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"));
channelsArray.put(channelJson);
}
// Convert the JSON array to a formatted string
String json = channelsArray.toString(4);
System.out.println(json);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
输出结果为:
[
{
"id": "1000028$3$0$0",
"name": "防区1",
"desc": "",
"status": "0",
"channelType": "0",
"channelSN": "",
"rights": "11000000000000000000000011101000000101100011111111111111111",
"alarmType": "80081",
"alarmLevel": "1"
}
]
该示例使用 dom4j 库解析 XML 字符串,并使用 JSONObject 和 JSONArray 类来构建 JSON 对象和数组。首先,将 XML 字符串解析为 Document 对象。然后,通过 XPath 表达式选择最后一个 Device 元素,并获取其中的 UnitNodes 元素。接下来,遍历 UnitNodes 元素中的所有 Channel 元素,将其属性转化为 JSON 对象,并添加到 JSON 数组中。最后,将 JSON 数组转化为格式化的 JSON 字符串输出。
原文地址: https://www.cveoy.top/t/topic/fRbd 著作权归作者所有。请勿转载和采集!