java 处理字符串格式的xml信息并给出代码和示例 xml信息为OrganizationDepartmentDepartmentDevicesDeviceDeviceDevice id=1000028 type=601 name=报警主机UnitNodes index=0 channelnum=60 type=3Channel id=1000028$3$0$0 name=防区1 desc=
以下是使用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/ieM4 著作权归作者所有。请勿转载和采集!