所需包:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3abd263bc2934df18f8ee5e24a777f09.png)
Test.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://www.example.org/web-app_2_5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.example.org/web-app_2_5 web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>cn.xiyoucloud.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
解析xml,测试一:
package cn.xiyoucloud.xmltest;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class DomServlet{
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document read = saxReader.read(new File("Test.xml"));
Element root = read.getRootElement();
@SuppressWarnings("unchecked")
List<Element> lists = root.elements();
for (Element e : lists) {
String name = e.getName();
System.out.println(name);
}
}
}
解析xml,测试二:
package cn.xiyoucloud.xmltest;
import java.io.File;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
public class SAXReaderTest {
public static void main(String[] args) throws DocumentException {
SAXReader saxReader = new SAXReader();
Document read = saxReader.read(new File("Test.xml"));
Element rootElement = read.getRootElement();
String version = rootElement.attributeValue("version");
System.out.println(version);
@SuppressWarnings("unchecked")
List<Element> lists = rootElement.elements();
for (Element list : lists) {
String element = list.getName();
if ("servlet".equals(element)) {
Element childElement = list.element("servlet-name");
String text = childElement.getText();
System.out.println(text);
String str = list.elementText("servlet-class");
System.out.println(str);
}
}
}
}