比如:<?xml version="1.0" encoding="UTF-8"?>
<group> <groupName>GN</groupName> <description>declaration</description> <person>
<name>Wang</name>
<age>23</age>
</person> <person>
<name>Li</name>
<age>24</age>
</person></group>
我只想打印person的name和age,不想遍历!
<group> <groupName>GN</groupName> <description>declaration</description> <person>
<name>Wang</name>
<age>23</age>
</person> <person>
<name>Li</name>
<age>24</age>
</person></group>
我只想打印person的name和age,不想遍历!
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
InputStream is = new FileInputStream(
"WebRoot/WEB-INF/某某某.xml");
Document doc = builder.parse(is); XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr
= xpath.compile("//person/name/text()|//person/age/text()"); 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).getNodeValue());
}
不知道是不是你想要的那种。
LS不是用dom4j的啊,能用dom4j实现么?辛苦了
如果有时间的话LZ还是研究一下吧,我这比较忙。休息了一会我才来逛逛的。
GOOD LUCK......
package xml;import java.io.File;
import java.io.IOException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class Dom4j {
private SAXReader reader ;
private Document document;
private static String path = "c:/bbc.xml"; //查找
public Dom4j(String str) throws DocumentException {
reader = new SAXReader();
document = reader.read(new File(str));
} //查找指定节点
public void getInfo() {
Element root = document.getRootElement();
List<Element> list = root.elements();
//Element e = root.element("person");
for(int i=0;i<list.size();i++) {
if("person".equals(list.get(i).getName())) {
String name = list.get(i).elementText("name");
String age = list.get(i).elementText("age");
System.out.println(name+":"+age);
}
}
} /**
* @param args
* @throws DocumentException
* @throws IOException
*/
public static void main(String[] args) throws DocumentException, IOException {
// TODO Auto-generated method stub
Dom4j test = new Dom4j(path);
test.getInfo();
}
}
QName qname = new QName("person");
List<Element> list = root.elements(qname);
for(int i= 0;i<list.size();i++) {
System.out.println(list.get(i).elementText("name") +":"+list.get(i).elementText("age"));
}