本章讲解如何拿到xml文件中值。
属性中的值:sqlMapConfig.xml
想拿到数据库的配置信息中name和value的属性值,比如拿到dirverClass和com.mysql.jdbc.Driver
文本中的值:taobao TaoBaoServlet taobao /taobao
想拿到 taobao TaoBaoServlet /taobao 这些信息
1.1、读取XML文档public static document load(String filename) {
document document = null;
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(new File(filename));
} catch (Exception ex) {
ex.printStackTrace();
}
return document;
}
public static document load(URL url) {
document document = null;
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(url);
} catch (Exception ex) {
ex.printStackTrace();
}
return document;
}
public static void main(String[] args) {
//方式一:load(String filename)
String absolutPath = XmlAnalysis.class.getResource("/").getPath()+"sqlMapConfig.xml"; // XmlAnalysis 为当前类名 获取当前类的绝对路径
absolutPath.replaceAll("\\","/");
load(absolutPath);
//方式二:load(URL url)
URL resource = XmlAnalysis.class.getClassLoader().getResource("sqlMapConfig.xml");
load(resource);
}
两种方式都可以,根据需求选用。
1.2.1、拿到xml节点属性中的值//获取根节点 Element rootElement = document.getRootElement(); //获取到 property 集合 ListpropertyList = rootElement.selectNodes("//property"); //拿到解析出的propertyList的值 propertyList.stream().forEach(element->{ System.out.println(element.attribute("name").getValue()); System.out.println(element.attributevalue("value")); });
element.attribute(“name”).getValue() 和 element.attributevalue(“value”)两种获取方式等价。
1.2.2、 拿到节点文本中的值//获取根节点 Element rootElement = document.getRootElement(); //获取到 selectNodes 集合 ListselectNodes = rootElement.selectNodes("//servlet"); selectNodes.stream().forEach(element -> { //获取 servlet-name 节点 Element ServletNameElement = (Element) element.selectSingleNode("servlet-name"); //获取节点的值 String ServletName = ServletNameElement.getStringValue(); System.out.println(ServletName); });
使用 getStringValue
1.3、 获取属性值和文本内容想要拿到 namespace的值和id、resultType、paramterType的属性值 和 sql语句
UserMapper.xml
Java代码:
URL resource = XmlAnalysis.class.getClassLoader().getResource("UserMapper.xml");
document document = load(resource);
Element rootElement = document.getRootElement();
String namespace = rootElement.attributevalue("namespace");
System.out.println(namespace);
List selectlist = rootElement.selectNodes("select");
selectlist.stream().forEach(select ->{
System.out.println(select.attributevalue("id"));
System.out.println(select.attributevalue("paramterType"));
System.out.println(select.attributevalue("resultType"));
System.out.println(select.getTextTrim());
});
使用 attributevalue 和 getTextTrim
本章完…



