本文主要是介绍dom4j-dom-sax解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
<?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>MyServlet1</servlet-name><servlet-class>cn.itheima.web.servlet1.MyServlet1</servlet-class></servlet><servlet-mapping><servlet-name>MyServlet1</servlet-name><url-pattern>/myServlet1</url-pattern></servlet-mapping><servlet><servlet-name>MyServlet2</servlet-name><servlet-class>cn.itheima.web.servlet1.MyServlet2</servlet-class></servlet><servlet-mapping><servlet-name>MyServlet2</servlet-name><url-pattern>/myServlet2</url-pattern></servlet-mapping>
</web-app>
利用dom4j进行xml解析
package cn.itheima.xml.dom4j;import java.util.List;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;public class TestDom4j {@Testpublic void testReadWebXML() {try {// 1.获取解析器SAXReader saxReader = new SAXReader();// 2.获得document文档对象Document doc = saxReader.read("src/cn/itheima/web/servlet1/web.xml");// 3.获取根元素Element rootElement = doc.getRootElement();// System.out.println(rootElement.getName());//获取根元素的名称// System.out.println(rootElement.attributeValue("version"));//获取根元素中的属性值// 4.获取根元素下的子元素List<Element> childElements = rootElement.elements();// 5.遍历子元素for (Element element : childElements) {//6.判断元素名称为servlet的元素if ("servlet".equals(element.getName())) {//7.获取servlet-name元素Element servletName = element.element("servlet-name");//8.获取servlet-class元素Element servletClass = element.element("servlet-class");System.out.println(servletName.getText());System.out.println(servletClass.getText());}}} catch (DocumentException e) {e.printStackTrace();}}}
输出如下:
MyServlet1
cn.itheima.web.servlet1.MyServlet1
MyServlet2
cn.itheima.web.servlet1.MyServlet2
通过解析xml配置文件,利用反射获取对象,然后在执行对象方法
package cn.itheima.web.servlet1;public interface IMyServlet {public void init();public void service();public void destory();
}
package cn.itheima.web.servlet1;public class MyServlet1 implements IMyServlet{@Overridepublic void init() {System.out.println("MyServlet1诞生了……");}@Overridepublic void service() {System.out.println("MyServlet1开始服务了……");}@Overridepublic void destory() {System.out.println("MyServlet1销毁了……");}}
package cn.itheima.web.servlet1;import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;public class TestMyServlet {@Testpublic void testMyServlet(){try {//1.创建解析器对象SAXReader saxReader = new SAXReader();//2.使用解析器加载web.xml文件得到document对象Document document = saxReader.read("src/cn/itheima/web/servlet1/web.xml");//3.获取根元素节点Element rootElement = document.getRootElement();//4.根据元素名称获取子元素节点Element servletElement = rootElement.element("servlet");//5.根据元素名称获取servlet-class的文本节点String servletClass = servletElement.element("servlet-class").getText();//System.out.println(servletClass);//6.通过类全名获取字节码文件Class clazz = Class.forName(servletClass);//7.创建实例对象MyServlet1 my = (MyServlet1) clazz.newInstance();//8.调用实例对象里面的方法my.init();my.service();my.destory();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}
输出如下:
MyServlet1诞生了……
MyServlet1开始服务了……
MyServlet1销毁了……
dom解析
配置文件放在项目根目录下,跟src平行
<?xml version="1.0" encoding="UTF-8"?>
<bookstore><book category="children"><title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book><book category="cooking"><title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book><book category="web"><title lang="en">Learning XML</title> <author>Erik T. Ray</author> <year>2003</year> <price>39.95</price> </book><book category="web"><title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book></bookstore>
package cn.itheima.xml.dom4j;import java.io.File;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;public class DomTest1
{public static void main(String[] args) throws Exception{// step 1:获得DOM解析器工厂// 工厂的作用是创建具体的解析器DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();// step 2:获得具体的dom解析器DocumentBuilder db = dbf.newDocumentBuilder();// step 3:解析一个xml文档,获得Document对象(根节点)// 此文档放在项目目录下即可Document document = db.parse(new File("NewFile.xml"));// 根据标签名访问节点NodeList list = document.getElementsByTagName("book");System.out.println("list length: " + list.getLength());// 遍历每一个节点for (int i = 0; i < list.getLength(); ++i){System.out.println("----------------------");// 获得元素,将节点强制转换为元素Element element = (Element) list.item(i);// 此时element就是一个具体的元素// 获取子元素:子元素title只有一个节点,之后通过getNodeValue方法获取节点的值String content0 = element.getElementsByTagName("title").item(0).getNodeValue();System.out.println(content0);// 此处打印出为null// 因为节点getNodeValue的值永远为null// 解决方法:加上getFirstChild() public Node item(int index);String content = element.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();System.out.println("title: " + content);// 此处打印出书名// 后面类似处理即可:content = element.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();System.out.println("author: " + content);content = element.getElementsByTagName("year").item(0).getFirstChild().getNodeValue();System.out.println("year: " + content);content = element.getElementsByTagName("price").item(0).getFirstChild().getNodeValue();System.out.println("price: " + content);}}}
list length: 4
----------------------
null
title: Harry Potter
author: J K. Rowling
year: 2005
price: 29.99
----------------------
null
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
price: 30.00
----------------------
null
title: Learning XML
author: Erik T. Ray
year: 2003
price: 39.95
----------------------
null
title: XQuery Kick Start
author: James McGovern
year: 2003
price: 49.99
sax解析
配置文件在src目录下,不是平级
<?xml version="1.0" encoding="UTF-8"?> <root> <student id="1" group="1"> <name>张三</name> <sex>男</sex> <age>18</age> <email>zhangsan@163.com</email> <birthday>1987-06-08</birthday> <memo>好学生</memo> </student> <student id="2" group="2"> <name>李四</name> <sex>女</sex> <age>18</age> <email>lisi@163.com</email> <birthday>1987-06-08</birthday> <memo>好学生</memo> </student> <student id="3" group="3"> <name>小王</name> <sex>男</sex> <age>18</age> <email>xiaowang@163.com</email> <birthday>1987-06-08</birthday> <memo>好学生</memo> </student> <student id="4" group="4"> <name>小张</name> <sex>男</sex> <age>18</age> <email>xiaozhang@163.com</email> <birthday>1987-06-08</birthday> <memo>好学生</memo> </student> <student id="5" group="5"> <name>小明</name> <sex>男</sex> <age>18</age> <email>xiaoming@163.com</email> <birthday>1987-06-08</birthday> <memo>好学生</memo> </student> </root>
package cn.itheima.xml.dom4j;
public class Student { private int id; private int group; private String name; private String sex; private int age; private String email; private String memo; private String birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public int getGroup() { return group; } public void setGroup(int group) { this.group = group; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } }
package cn.itheima.xml.dom4j;
import java.util.ArrayList;
import java.util.List; import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; /** * 功能描述:采用sax方式解析XML<br> * * @author sxyx2008 * */
public class SaxParseXml extends DefaultHandler{ //存放遍历集合 private List<Student> list; //构建Student对象 private Student student; //用来存放每次遍历后的元素名称(节点名称) private String tagName; public List<Student> getList() { return list; } public void setList(List<Student> list) { this.list = list; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public String getTagName() { return tagName; } public void setTagName(String tagName) { this.tagName = tagName; } //只调用一次 初始化list集合 @Override public void startDocument() throws SAXException { list=new ArrayList<Student>(); } //调用多次 开始解析 @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if(qName.equals("student")){ student=new Student(); //获取student节点上的id属性值 student.setId(Integer.parseInt(attributes.getValue(0))); //获取student节点上的group属性值 student.setGroup(Integer.parseInt(attributes.getValue(1))); } this.tagName=qName; } //调用多次 @Override public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equals("student")){ this.list.add(this.student); } this.tagName=null; } //只调用一次 @Override public void endDocument() throws SAXException { } //调用多次 @Override public void characters(char[] ch, int start, int length) throws SAXException { if(this.tagName!=null){ String date=new String(ch,start,length); if(this.tagName.equals("name")){ this.student.setName(date); } else if(this.tagName.equals("sex")){ this.student.setSex(date); } else if(this.tagName.equals("age")){ this.student.setAge(Integer.parseInt(date)); } else if(this.tagName.equals("email")){ this.student.setEmail(date); } else if(this.tagName.equals("birthday")){ this.student.setBirthday(date); } else if(this.tagName.equals("memo")){ this.student.setMemo(date); } } }
}
package cn.itheima.xml.dom4j;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import java.io.IOException;
import java.io.InputStream;
import java.util.List; public class Test { public static void main(String[] args) { SAXParser parser = null; try { //构建SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); //实例化 DefaultHandler对象 SaxParseXml parseXml=new SaxParseXml(); //加载资源文件 转化为一个输入流 InputStream stream=SaxParseXml.class.getClassLoader().getResourceAsStream("student.xml"); //调用parse()方法 parser.parse(stream, parseXml); //遍历结果 List<Student> list=parseXml.getList(); for(Student student:list){ System.out.println("id:"+student.getId()+"\tgroup:"+student.getGroup()+"\tname:"+student.getName()+"\tsex:"+student.getSex()+"\tage:"+student.getAge()+"\temail:"+student.getEmail()+"\tbirthday:"+student.getBirthday()+"\tmemo:"+student.getMemo()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
id:1 group:1 name:张三 sex:男 age:18 email:zhangsan@163.com birthday:1987-06-08 memo:好学生
id:2 group:2 name:李四 sex:女 age:18 email:lisi@163.com birthday:1987-06-08 memo:好学生
id:3 group:3 name:小王 sex:男 age:18 email:xiaowang@163.com birthday:1987-06-08 memo:好学生
id:4 group:4 name:小张 sex:男 age:18 email:xiaozhang@163.com birthday:1987-06-08 memo:好学生
id:5 group:5 name:小明 sex:男 age:18 email:xiaoming@163.com birthday:1987-06-08 memo:好学生
这篇关于dom4j-dom-sax解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!