import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
/**
* @author shiqil.liu
* @date 2019-08-21 17:05
*/
public class DealXml {
private static Logger logger = LoggerFactory.getLogger(DealXml.class);
/* public static void main(String[] args) {
try {
Document doc=loadDocument("aaa.xml");
XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
XPath xpath = factory.newXPath();
XPathExpression compile = xpath.compile("//import");//一个斜线代表一层,应该也可以写成//import!
NodeList nodes = (NodeList)compile.evaluate(doc, XPathConstants.NODESET);//获取student节点的所有节点
for(int i=0;i<nodes.getLength();i++) {
Element item = (Element) nodes.item(i);
String s1 = item.getAttribute("resource");
System.out.println(s1);
}
} catch (Exception e) {
e.printStackTrace();
}
//org.dom4j.io.SAXReader reader = new SAXReader(); 从inputStream读取
//Document doc = reader.read(inputStream);
}*/
public static void main(String[] args) {
try {
Document doc = loadDocument("bbb.xml");
XPathFactory factory = XPathFactory.newInstance();//实例化XPathFactory对象
XPath xpath = factory.newXPath();
XPathExpression compile = xpath.compile("//form");//一个斜线代表一层,应该也可以写成//import!
NodeList nodes = (NodeList) compile.evaluate(doc, XPathConstants.NODESET);//获取student节点的所有节点
for (int i = 0; i < nodes.getLength(); i++) {
Element item = (Element) nodes.item(i);
String s1 = item.getAttribute("controller");
String s2 = item.getAttribute("action");
System.out.println(s1 + "_" + s2);
NodeList childNodes = item.getElementsByTagName("property");
//NodeList childNodes = item.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Element item1 = (Element) childNodes.item(j);
String ss1 = item1.getAttribute("name");
String ss2 = item1.getAttribute("option");
String ss3 = item1.getAttribute("regex");
String ss4 = item1.getAttribute("message");
System.out.println(ss1 + "_" + ss2 + "_" + ss3 + "_" + ss4);
}
System.out.println("");
System.out.println("---------------------------------");
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
//org.dom4j.io.SAXReader reader = new SAXReader(); 从inputStream读取
//Document doc = reader.read(inputStream);
}
private static Document loadDocument(String path) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();//实例化DocumentBuilderFactory对象
DocumentBuilder builder = dbf.newDocumentBuilder();
File file = new File(Thread.currentThread().getContextClassLoader().getResource(path).getPath());
if (file.exists()) {
return builder.parse(file);
} else {
logger.warn("配置文件没有被找到{}", path);
return null;
}
}
}