import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class Dom4JTest
{
public static void main (String[] args)
{
String PATH = System.getProperty("user.dir")+File.separator;
SAXReader reader = new SAXReader();
try
{
Document dom = reader.read(new FileInputStream(PATH+"web.xml"));
System.out.println(dom.asXML());
Node node = dom.selectSingleNode("//context-param/param-name");
System.out.println(node.getText());
String value = dom.valueOf("//context-param/param-value");
System.out.println(value);
System.out.println("-----------------------------------");
List<Node> list = dom.selectNodes("//servlet");
for (Node node2 : list)
{
String name2 = node2.valueOf("servlet-name");
String value2 = node2.valueOf("servlet-class");
System.out.println(name2+":"+value2);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (DocumentException e)
{
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?> <web-app> <context-param> <param-name>name</param-name> <param-value>this is the context param value</param-value> </context-param> <servlet> <servlet-name>TestServlet1</servlet-name> <servlet-class>TestServlet1</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>TestServlet2</servlet-name> <servlet-class>TestServlet2</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet> <servlet-name>TestServlet3</servlet-name> <servlet-class>TestServlet3</servlet-class> <load-on-startup>3</load-on-startup> </servlet> <servlet> <servlet-name>TestServlet4</servlet-name> <servlet-class>TestServlet4</servlet-class> <load-on-startup>4</load-on-startup> </servlet> </web-app>