java dom解析XML(soap报文) 并转为json

/**

* 

Title: Dom4Test.java

  *

Description:

  *

Copyright: Copyright (c) 2019

  *

Company: mp.csdn.net

  * @author dxy * @date 2020年3月31日   * @version 1.0   */ package com.dxy.test; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** *

Title: Dom4Test

*

Description:

* @author dxy * @date 2020年3月31日 */ public class Dom4Test { public static void main(String[] args) { // TODO Auto-generated method stub String strXml = "{\"message\":\"数据成功\",\"statusCode\":\"S\"}"; parserXml(strXml); } public static void parserXml(String strXml) { try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(new InputSource(new StringReader(strXml))); NodeList sessions = document.getChildNodes(); /*HashMap hash=new HashMap();*/ String json=""; for (int i = 0; i < sessions.getLength(); i++) { Node session = sessions.item(i); NodeList sessionInfo = session.getChildNodes(); for (int j = 0; j < sessionInfo.getLength(); j++) { Node node = sessionInfo.item(j); NodeList sessionMeta = node.getChildNodes(); for (int k = 0; k < sessionMeta.getLength(); k++) { System.out.println(sessionMeta.item(k).getTextContent()); json=sessionMeta.item(k).getTextContent(); // hash.put(sessionMeta.item(k).getNodeName(), sessionMeta.item(k).getTextContent()); } } } System.out.println("获取json"+json); try { JSONObject result=new JSONObject(json); //result.get("message"); //result.get("statusCode"); if(result.get("statusCode").equals("S")) { System.out.println(result.get("message")); }else { System.out.println("失败"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("解析完毕"); } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } }

 

你可能感兴趣的:(后台)