dom4j解析xml
使用xpath解析指定节点数据,适用多层子节点遍历
1.依赖的jar包
<dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.6</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
2.示例xml
<?xml version="1.0" encoding="UTF-8"?> <Doc> <a> <a1>a1</a1> <a2>a2</a2> <a3> <a31>龙妈</a31> <a32>卓跟</a32> </a3> <a3> <a31>穷</a31> <a32>小白</a32> </a3> </a> <a> <a1>a11</a1> <a2>a21</a2> <a3> <a31>龙妈和穷</a31> <a32>三龙齐飞</a32> </a3> <a3> <a31>铁王座</a31> <a32>穷</a32> </a3> </a> </Doc>
3.读取xml
SAXReader reader = new SAXReader(); Document doc = reader.read("D:\\1.xml"); //获取xml中节点名为a的所有节点,不能为根节点 List<Element> aList = doc.selectNodes("//a"); for (int i=0;i<aList.size();i++){ Element a = aList.get(i); //selectSingleNode只适用于1:1 //只会存在一个节点,如存在多个节点使用selectNodes Element a1 = (Element)a.selectSingleNode("a1"); Element a2 = (Element)a.selectSingleNode("a2");
//此处根据实际xml数据判断a1,a2节点是否=null,如果是必有节点,无需判断
//if(a1==null) continue;
//根据业务逻辑取对应节点数据,只筛选a1=a11的数据 if (!"a11".equals(a1.getTextTrim())) { continue; } System.out.println("a2= "+a2.getTextTrim()); //多个子节点,使用此方法, List<Element> a3List = a.selectNodes("a3"); for (int j=0;j<a3List.size();j++){ Element a3 = a3List.get(j); Element a31 = (Element) a3.selectSingleNode("a31"); Element a32 = (Element) a3.selectSingleNode("a32"); System.out.println("a31= "+a31.getTextTrim()); System.out.println("a32= "+a32.getTextTrim()); } }
打印如下:
a2= a21 a31= 龙妈和穷 a32= 三龙齐飞 a31= 铁王座 a32= 穷