Java XML转换为JSON XML解析 转换为JSON Java 实现JSON转换为XML json转xml
一、转换代码
1、XML字符串转换为JSON
/**
* description: XML字符串转换为JSON
* @param strXML
* @throws Exception
* @return Map<String,String>
* @version v1.0
* @author w
* @date 2022/12/30 17:35
*/
public static Map<String, String> xmlToMap(String strXML) throws Exception {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
org.w3c.dom.Document doc = documentBuilder.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getDocumentElement().getChildNodes();
for (int idx=0; idx<nodeList.getLength(); ++idx) {
Node node = nodeList.item(idx);
if (node.getNodeType() == Node.ELEMENT_NODE) {
org.w3c.dom.Element element = (org.w3c.dom.Element) node;
data.put(element.getNodeName(), element.getTextContent());
}
}
try {
stream.close();
}
catch (Exception ex) {
}
return data;
}
2、JSON 字符串转换为xml
/**
* description: JSON 字符串转换为xml
* @param data
* @throws Exception
* @return String
* @version v1.0
* @author w
* @date 2022/12/30 17:45
*/
public static String mapToXml(Map<String, Object> data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.newDocument();
org.w3c.dom.Element root = document.createElement("xml");
document.appendChild(root);
for (String key: data.keySet()) {
Object value = data.get(key);
if (value == null) {
value = "";
}
String val = value.toString().trim();
org.w3c.dom.Element filed = document.createElement(key);
filed.appendChild(document.createTextNode(val));
root.appendChild(filed);
}
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
DOMSource source = new DOMSource(document);
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
transformer.transform(source, result);
String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
try {
writer.close();
}
catch (Exception ex) {
}
return output;
}
二、代码转换测试
1、xml 字符串转换为 json
/**
* Description: xml 字符串转换为 json
* @return void
* @version v1.0
* @author wu
* @date 2022/12/30 17:55
*/
@Test
public void xmlToJsonTest() throws Exception {
String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<o>\n" +
" <id type=\"number\">123</id>\n" +
" <name type=\"string\">哈哈name</name>\n" +
"</o>" ;
final Map<String, String> map = xmlToMap(xmlStr);
System.out.println("map="+ map);
// 转换为json字符串
System.out.println(JSON.toJSONString(map));
}
1.1、输出结果如下:
map={name=哈哈name, id=123}
{"name":"哈哈name","id":"123"}
2、 json 转换为 xml 字符串
/**
* Description: json 转换为 xml 字符串
* @return void
* @version v1.0
* @author wu
* @date 2022/12/30 18:08
*/
@Test
public void jsonToXmlTest() throws Exception {
String jsonStr = "{\"name\":\"哈哈name\",\"id\":\"123\"}\n";
final JSONObject jsonObject = JSON.parseObject(jsonStr);
final String s = mapToXml(jsonObject);
System.out.println(s);
}
2.1、输出结果如下:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<xml>
<name>哈哈name</name>
<id>123</id>
</xml>
网页版有现成的工具:XML转JSON,JSON转XML - SO JSON在线工具