天天看點

XML格式請求傳回資料轉為json資料

 需要引入dom4j包

<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->

        <dependency>

            <groupId>dom4j</groupId>

            <artifactId>dom4j</artifactId>

            <version>1.6.1</version>

        </dependency>

/**
 * xml工具
 * @author tangbin
 * @date 2021年5月8日
 */
public class XMLUtils {
	
		/**
		 * 将xml格式處理為jsonObject對象
		 * @param resString xml格式
		 * @return
		 * @throws UnsupportedEncodingException
		 * @throws DocumentException
		 */
		public static JSONObject xmlHandle(String resString) throws UnsupportedEncodingException, DocumentException {
			
			// 讀取輸入流
			SAXReader reader = new SAXReader();
			Document document = null;
			document = reader.read(new ByteArrayInputStream(resString.getBytes("UTF-8")));
	
			// 得到xml根元素
			Element root = document.getRootElement();
			
			JSONObject resJsonObject = elementHandle(root);
			
			return resJsonObject;
		}
		
		/**
		 * 遞歸取每一層資料
		 * @param element
		 * @return
		 */
		private static JSONObject elementHandle(Element element) {
			
			JSONObject resultJsonObject = new JSONObject();
			// 得到根元素的所有子節點
			@SuppressWarnings("unchecked")
			List<Element> elementList = element.elements();
			
			// 周遊所有子節點
			for (Element e : elementList){
				
				String name = e.getName();
				String text = e.getText();
				if(e.hasContent() && !e.isTextOnly()) {
	
					//有下一層
					resultJsonObject.element(name, elementHandle(e));
						
				}
				else {
					
					resultJsonObject.element(name, text);
					
				}
			}
			
			return resultJsonObject;
		}
}