本文使用javax.xml.parsers
包下的DocumentBuilderFactory
构建解析工具解析xml。
首先我们通过工厂构建一个Document
private static File file = new File("e:/data.xml");
public Document build(){
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
Document document = null;
try {
docBuilder = dbFactory.newDocumentBuilder();
document = docBuilder.parse(file);
} catch (SAXException | ParserConfigurationException | IOException e) {
e.printStackTrace();
}
assert document != null;
document.normalize();
return document;
}
解析数据
//通过build函数拿到document对象
Document document = build();
//获取到根节点
Element root = document.getDocumentElement();
//通过根节点获取根节点下的所有节点
NodeList childNodes = root.getChildNodes();
//获取根节点的子节点个数
int length = childNodes.getLength();
//创建一个存储数据的容器,用来存储解析的结果
Map<String, Object> data = new HashMap<>();
//如果根节点下包含大于一个的节点,递归获取数据
if(length > 1){
data.put(root.getTagName(),readXmlList(childNodes));
}else{
//根节点下就一个节点,直接获取
Node item = childNodes.item(0);
String nodeName = item.getNodeName();
String textContent = item.getTextContent();
Map<String, String> childMap = new HashMap<>();
childMap.put(nodeName,textContent);
data.put(root.getTagName(),childMap);
}
递归获取数据
private Map<String,Object> readXmlList(NodeList nodeList){
final Map<String, Object> result = new HashMap<>();
int length = nodeList.getLength();
for(int i=0;i<length;i++){
Node node = nodeList.item(i);
if(node.getNodeType()==Node.ELEMENT_NODE) {
NodeList childNodes = node.getChildNodes();
if(childNodes.getLength() > 1){
result.put(node.getNodeName(),readXmlList(childNodes));
}else{
String nodeName = node.getNodeName();
String textContent = node.getTextContent();
result.put (nodeName,textContent);
}
}
}
return result;
}
这种方式可以适配多个子节点或多级子节点情况。
create by 旗红
网友评论