java学习之xml

xml的处理有两种方式dom和Sax

其中dom有3套api ,分别是dom和jdom和dom4j 

 1 package com.gh.xml;
 2 
 3 import java.io.File;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import javax.xml.parsers.DocumentBuilder;
 8 import javax.xml.parsers.DocumentBuilderFactory;
 9 
10 import org.w3c.dom.Document;
11 import org.w3c.dom.Node;
12 import org.w3c.dom.NodeList;
13 /**
14  * Dom模式读取xml
15  * @author ganhang
16  *
17  */
18 public class DomDemo {
19     public static void main(String[] args) throws Exception {
20         // 创建dom解析器工厂
21         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
22         // 创建一个dom解析器
23         DocumentBuilder db = dbf.newDocumentBuilder();
24         // 关联文件
25         File f = new File("src/1.xml");
26         // 开始解析
27         Document doc = db.parse(f);// 传文件或者字节流
28         // 根据节点获取数据
29         NodeList nl = doc.getElementsByTagName("teacher");
30         List<Teacher> teachers = new ArrayList<Teacher>();
31         Teacher t = null;
32         for (int i = 0; i < nl.getLength(); i++) {
33             Node teacherNode = nl.item(i);// 获取每个teacher节点
34             // 得到节点的属性id的值
35             String str = teacherNode.getAttributes().getNamedItem("id")
36                     .getNodeValue();
37             //System.out.println(str);
38             t = new Teacher();
39             t.setId(Integer.parseInt(str));
40             // 获取teacher节点下的所有子节点
41             NodeList childNodeList = teacherNode.getChildNodes();
42             //System.out.println(childNodeList.getLength());
43             for (int j = 0; j < childNodeList.getLength(); j++) {
44                 // 注意teacher有三个子节点#text name #text
45                 Node childNode = childNodeList.item(j);
46                 //System.out.println(childNode.getNodeName());
47                 // 取name的子节点的值
48                 if ("name".equals(childNode.getNodeName())) {
49                     t.setName(childNode.getFirstChild().getNodeValue());
50                 }
51             }
52             teachers.add(t);
53         }
54         System.out.println(teachers);
55     }
56 }
 1 package com.gh.xml;
 2 
 3 import java.io.InputStream;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 import org.jdom2.Document;
 8 import org.jdom2.Element;
 9 import org.jdom2.input.SAXBuilder;
10 
11 public class JdomDemo {
12     public static void main(String[] args) throws Exception {
13         SAXBuilder sb = new SAXBuilder();// 创建jdom解析器
14         InputStream in = Thread.currentThread().getContextClassLoader()
15                 .getResourceAsStream("1.xml");
16         Document doc = sb.build(in);
17         //拿根元素
18         Element roote = doc.getRootElement();
19         //根据根元素拿子元素
20         List<Element> liste = roote.getChildren();
21         List<Teacher> teachers=new ArrayList<Teacher>();
22         Teacher t=null;//注意必须要在里面new,不然teachers添加的都是重复的t;
23         //遍历子元素,也可以返回一个iterator遍历;
24         for (int i = 0; i < liste.size(); i++) {
25             t=new Teacher();
26             Element e = liste.get(i);
27             t.setId(Integer.parseInt(e.getAttributeValue("id")));
28             t.setName(e.getChildText("name"));
29             teachers.add(t);
30         }
31         System.out.println(teachers);
32     }
33 }
 1 package com.gh.xml;
 2 
 3 import java.io.File;
 4 import java.util.ArrayList;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 import org.dom4j.Document;
 9 import org.dom4j.Element;
10 import org.dom4j.io.SAXReader;
11 /**
12  * Dom4j 性能最好
13  * @author ganhang
14  *
15  */
16 public class Dom4jDemo {
17     public static void main(String[] args) throws Exception {
18         SAXReader sr=new SAXReader();
19         File f=new File("src/1.xml");
20         Document doc=sr.read(f);
21         Element roote=doc.getRootElement();
22         Iterator<Element> iters=roote.elementIterator();
23         Teacher t=null;
24         List<Teacher> list=new ArrayList<Teacher>();
25         while(iters.hasNext()){
26             t=new Teacher(); 
27             Element e=iters.next();
28             t.setId(Integer.parseInt(e.attributeValue("id")));
29             t.setName(e.elementText("name"));
30             list.add(t);
31         }
32         System.out.println(list);
33     }
34 }
 1 package com.gh.xml;
 2 
 3 import java.io.InputStream;
 4 
 5 import javax.xml.parsers.SAXParser;
 6 import javax.xml.parsers.SAXParserFactory;
 7 /**
 8  * SAX读xml
 9  * @author ganhang
10  *
11  */
12 public class SaxDemo {
13     public static void main(String[] args) throws Exception {
14         //创建SAX解析器工厂
15         SAXParserFactory spf = SAXParserFactory.newInstance();
16         //创建sax解析器
17         SAXParser sp = spf.newSAXParser();
18         //用字符流读xml
19         InputStream is = Thread.currentThread().getContextClassLoader()
20                 .getResourceAsStream("1.xml");
21         MyHandler dh=new MyHandler();//实例化引擎
22         //开始解析
23         sp.parse(is, dh);
24         System.out.println(dh.getList());
25         
26     }
27 }
 1 package com.gh.xml;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 import org.xml.sax.Attributes;
 7 import org.xml.sax.SAXException;
 8 import org.xml.sax.helpers.DefaultHandler;
 9 /**
10  * Sax模式的事件处理引擎
11  * @author ganhang
12  *
13  */
14 public class MyHandler extends DefaultHandler {
15     private List<Teacher> list = null;
16     private Teacher t = null;
17     private String flag = null;
18     //开始读入文件
19     @Override
20     public void startDocument() throws SAXException {
21         list=new ArrayList<Teacher>();
22     }
23     //开始读元素
24     @Override
25     public void startElement(String uri, String localName, String qName,
26             Attributes attributes) throws SAXException {
27         flag = qName;
28         if ("teacher".equals(qName)) {
29             t=new Teacher();//注意要在这new一个新的Teacher不然list添加会重复
30             t.setId(Integer.parseInt(attributes.getValue("id")));
31             //System.out.println(t.getId());
32         }
33     }
34     //读字符数据
35     @Override
36     public void characters(char[] ch, int start, int length)
37             throws SAXException {
38         if ("name".equals(flag)) {
39             t.setName(new String(ch, start, length));
40              //System.out.println(t.getName());
41         }
42     }
43     //结束元素时干嘛
44     @Override
45     public void endElement(String uri, String localName, String qName)
46             throws SAXException {
47         if ("teacher".equals(qName)) {
48             list.add(t);
49             //System.out.println(list.get(0));
50         }//System.out.println(t);
51             flag = null;
52     }
53     //结束文件时干嘛
54     @Override
55     public void endDocument() throws SAXException {
56         System.out.println("解析成功!");
57         //System.out.println(list.get(0));
58     }
59     public List<Teacher> getList() {
60         return list;
61     }
62 
63 }
 1 package com.gh.xml;
 2 
 3 public class Teacher {
 4     private int id;
 5     private String name;
 6     
 7     public int getId() {
 8         return id;
 9     }
10     public void setId(int id) {
11         this.id = id;
12     }
13     public String getName() {
14         return name;
15     }
16     public Teacher(int id, String name) {
17         this.id = id;
18         this.name = name;
19     }
20     public Teacher() {
21         super();
22     }
23     public void setName(String name) {
24         this.name = name;
25     }
26     @Override
27     public String toString() {
28         return "Teacher [id=" + id + ", name=" + name + "]";
29     }
30 }
 1 package com.gh.xml;
 2 
 3 import java.beans.XMLDecoder;
 4 import java.beans.XMLEncoder;
 5 import java.io.BufferedInputStream;
 6 import java.io.BufferedOutputStream;
 7 import java.io.File;
 8 import java.io.FileInputStream;
 9 import java.io.FileOutputStream;
10 /**
11  * xml和对象之间的转换
12  * @author ganhang
13  *
14  */
15 public class ObjectAndXmlDemo {
16     /**
17      * 把对象转成xml
18      * @param obj
19      * @param file
20      * @throws Exception 
21      */
22     public static void object2xml(Teacher obj,File file) throws Exception{
23         BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(file));
24         XMLEncoder encode=new XMLEncoder(bos);
25         encode.writeObject(obj);
26         encode.flush();
27         encode.close();
28         bos.close();
29         System.out.println("写入成功");
30     }
31     /**
32      * xml转成对象
33      * @param file
34      * @return
35      * @throws Exception
36      */
37     public static Teacher xml2object(File file) throws Exception{
38         BufferedInputStream bis=new BufferedInputStream(new FileInputStream(file));
39         XMLDecoder decode =new XMLDecoder(bis);
40         Teacher t=(Teacher)decode.readObject();
41         decode.close();
42         bis.close();
43         System.out.println("读入成功");
44         return t;
45     }
46     public static void main(String[] args) throws Exception {
47         //Teacher t=new Teacher(1,"小白");
48         //object2xml(t,new File("src/2.xml"));
49         System.out.println(xml2object(new File("src/2.xml")));
50     }
51 }

1.xml

 

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <person>
 3     <teacher id="1">
 4         <name>小白</name>
 5         <desc>hehe1</desc>
 6     </teacher>
 7     
 8     <teacher id="2">
 9         <name>小黑</name>
10         <desc>hehe2</desc>
11     </teacher>
12     <teacher id="3">
13         <name>小红</name>
14         <desc>hehe3</desc>
15     </teacher>
16 </person>

2.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <java version="1.7.0_79" class="java.beans.XMLDecoder">
 3  <object class="com.gh.xml.Teacher">
 4   <void property="id">
 5    <int>1</int>
 6   </void>
 7   <void property="name">
 8    <string>小白</string>
 9   </void>
10  </object>
11 </java>

 

你可能感兴趣的:(java学习之xml)