欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java将xml转化成json案例

程序员文章站 2022-03-31 16:53:11
...

xml格式如下:

<plist version="1.0">
<array>
<dict>
<key>cities</key>
<array>
<dict>
<key>areas</key>
<array>
<dict>
<key>streets</key>
<array>
<string>东华门街道</string>
<string>景山街道</string>
<string>交道口街道</string>
<string>安定门街道</string>
<string>北新桥街道</string>
<string>东四街道</string>
<string>朝阳门街道</string>
<string>建国门街道</string>
<string>东直门街道</string>
<string>和平里街道</string>
<string>前门街道</string>
<string>崇文门外街道</string>
<string>东花市街道</string>
<string>龙潭街道</string>
<string>体育馆路街道</string>
<string>天坛街道</string>
<string>永定门外街道</string>
</array>
<key>county</key>
<string>东城区</string>
</dict>
<dict>
                      ......

通过dom4j解析xml,代码如下:

import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class XmlParser {
		
	public static void main(String[] args) throws Exception{
	JSONArray array = new JSONArray();	
	InputStream inputStream = XmlParser.class.getResourceAsStream("/area.xml");
	SAXReader reader = new SAXReader();   
	Document document = reader.read(inputStream);
	Element rootElement = document.getRootElement();
	parseXML(rootElement,array);
	System.out.println(array.toString());	
	inputStream.close();
	}	
	
	/**
	 * pengweikang 20180509 xml转化json
	 * @param element 根结点对象
	 * @param array json数组
	 */
	public static void parseXML(Element element,JSONArray array) {
		
		Element arrayElement = element.element("array");
		
		List<Element> listElmenet = arrayElement.elements();
		for(Element distElement :listElmenet) {
			JSONObject jsonObject = new JSONObject();
			List<Element> keysElements = null;	
			try {Element keyElement = distElement.element("string");jsonObject.put("name", keyElement.getText());} catch (Exception e1) {
				jsonObject.put("name", distElement.getText());
			}
			try {keysElements = distElement.elements("key");jsonObject.put("type", keysElements.get(0).getText());} catch (Exception e1) {}
			try {jsonObject.put("key", keysElements.get(1).getText());} catch (Exception e1) {}
			try {	
			List<Element> temparrayElements = distElement.element("array").elements();
			if(temparrayElements!= null && temparrayElements.size() > 0) {
				JSONArray temparray = new JSONArray();
				parseXML(distElement,temparray);//递归查找添加到JSON中
				jsonObject.put("array", temparray);
			}
			}catch(Exception e) {
				e.printStackTrace();
			}
			array.add(jsonObject);
		}
	}
}

生成的json如下:

[
  {
    "name": "北京市",
    "type": "cities",
    "key": "state",
    "array": [
      {
        "name": "北京市",
        "type": "areas",
        "key": "city",
        "array": [
          {
            "name": "东城区",
            "type": "streets",
            "key": "county",
            "array": [
              {
                "name": "东华门街道"
              ......