找到xml里面的所有某个名称的标签
xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<resource name="level1" >
<else></else>
<resource name="level2" >
<resource name="level3" >
</resource>
</resource>
</resource>
</resources>
StringBuilder builder = new StringBuilder();
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(new File(""));
Element root = document.getRootElement();
List<Element> list = root.selectNodes("//resource");
for (Element e : list) {
builder.append(e.attributeValue("name")).append(",");
}
Document doc = sax.build("test.xml");
Element rootEle = doc.getRootElement();
List resourcesList = XPath.selectNodes(rootEle, "//resources/resource");
// 循环list
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("src/test.xml");
XPathFactory xFactory = XPathFactory.newInstance();
XPath xpath = xFactory.newXPath();
XPathExpression expr = xpath.compile("//resource/@name");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getTextContent());
}