xml字符串解析为map
直接粘贴后改包名即可运行
// 包名自己改
package com.kun.leetcode.core.twe;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
/**
* @description:
* @author: kunT
* @create: 2022-02-09 10:13
*/
public class doc {
public static void main(String[] args) {
// 需要解析的xml字符串
String xml = "<Request>\n" +
" <Header>\n" +
" <SourceSystem>SYS0009</SourceSystem>\n" +
" <MessageID>0001</MessageID>\n" +
" </Header>\n" +
" <Body>\n" +
" <RegisterDocumentRt>\n" +
" <OrganizationCode>48500030-7</OrganizationCode>\n" +
" <BusinessFieldCode>00002</BusinessFieldCode>\n" +
" <PATPatientID>0010841465</PATPatientID>\n" +
" <PAADMVisitNumber>109971386</PAADMVisitNumber>\n" +
" </RegisterDocumentRt>\n" +
" </Body>\n" +
"</Request>";
HashMap<String, String> map = xmlValueToMap(xml);
System.out.println(map);
}
public static HashMap<String, String> xmlValueToMap(String xml) {
// 使用jdk自带的工具将xml字符串转化为document
HashMap<String, String> map = new HashMap<>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
Document parse = null;
try {
// 替换掉xml字符串中的空格和换行防止,清除错误的文本结点(可根据自己的需求修改不同替换元素)
String replace = xml.replaceAll("\n", "").replace(" ", "");
StringReader stringReader = new StringReader(replace);
parse = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader));
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
Element documentElement = parse.getDocumentElement();
valueToMap(map, documentElement);
return map;
}
private static void valueToMap(HashMap<String, String> map, Element documentElement) {
NodeList childNodes = documentElement.getChildNodes();
for(int i = 0 ; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
// 如果结点类型为3表示该结点为文本结点需要存入map,反之则继续遍历文档
if(item.getNodeType() == 3) {
// 将标签名为key, 文本节点的文本内容为value存入到map中
map.put(documentElement.getNodeName(), item.getTextContent());
} else {
valueToMap(map, (Element) item);
}
}
}
}