Java解析XML:Jdom解析和SAX解析

今天看了Java解析XML的几种方法,记录一下

    1、Jdom解析

      (1)读取XML内容

  

 1   private static void readXML() {
 2         // TODO Auto-generated method stub
 3         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
 4         try {
 5             Document document = JdomTools.getDocument("src/books.xml");
 6             // 找节点
 7             NodeList tagName = document.getElementsByTagName("name");
 8             Node item = tagName.item(1);
 9             // 获取节点文本
10             String textContent = item.getTextContent();
11             System.out.println(textContent);
12         } catch (Exception e) {
13             // TODO Auto-generated catch block
14             e.printStackTrace();
15         }
16     }

    (2)写入新节点

  

 1   public static void write2XML() {
 2         try {
 3             
 4             //获取要写入新节点的原dom树信息
 5             Document document = JdomTools.getDocument("src/books.xml");
 6             NodeList nodeList = document.getElementsByTagName("book");
 7             Node node = nodeList.item(0);
 8             //实例化一个新的节点对象
 9             Element element = document.createElement("nums");
10             element.setTextContent("132");
11             //追加到父节点中
12             node.appendChild(element);
13             //将修改后的新的dom覆盖掉原来的dom文件
14             JdomTools.write2Xml(document, "src/books.xml");
15         } catch (Exception e) {
16             // TODO Auto-generated catch block
17             e.printStackTrace();
18         }
19     }

  (3)移除子节点

 1  public static void removeNode(){
 2         try {
 3             Document document = JdomTools.getDocument("src/books.xml");
 4     ///方法一
 5             //Node node = document.getElementsByTagName("nums").item(0);
 6             
 7             //System.out.println(node.getParentNode().getTextContent());
 8             //node.getParentNode().removeChild(node);
 9     ///方法二
10             
11             JdomTools.deleteNode(document.getElementsByTagName("book").item(0),document.getElementsByTagName("nums").item(0));
12             JdomTools.write2Xml(document, "src/books.xml");
13         } catch (Exception e) {
14             // TODO Auto-generated catch block
15             e.printStackTrace();
16         }
17     }

  (4)替换子节点

 1  public static void replaceNode(){
 2         try {
 3             Document document = JdomTools.getDocument("src/books.xml");
 4             Element element = document.createElement("添加的");
 5             element.setTextContent("这是测试的内容");
 6             JdomTools.replaceNodeText(element, document.getElementsByTagName("price").item(0));
 7             JdomTools.write2Xml(document, "src/books.xml");
 8         } catch (Exception e) {
 9             // TODO Auto-generated catch block
10             e.printStackTrace();
11         }
12     }

  JdomTools工具类

 

 1 package com.xujingyang.utils;
 2 
 3 import javax.xml.parsers.DocumentBuilder;
 4 import javax.xml.parsers.DocumentBuilderFactory;
 5 import javax.xml.transform.Transformer;
 6 import javax.xml.transform.TransformerFactory;
 7 import javax.xml.transform.dom.DOMSource;
 8 import javax.xml.transform.stream.StreamResult;
 9 
10 import org.w3c.dom.DOMException;
11 import org.w3c.dom.Document;
12 import org.w3c.dom.Node;
13 
14 public class JdomTools {
15     
16     /**
17      * 查找document
18      * @param path
19      * @return
20      * @throws Exception 
21      */
22     public  static Document getDocument(String path) throws Exception{
23         // 获取DocumentBuilder实例
24         DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
25         // 获取document对象
26         return builder.parse(path);
27     }
28 
29     
30     /**
31      * 删除节点
32      * @param path
33      * @param oldChild
34      * @param document 
35      * @throws Exception
36      */
37     public static void deleteNode(Node document,Node oldChild ) throws Exception{
38         //移除document节点下的子节点
39         document.removeChild(oldChild);
40     }
41     
42     /**
43      * 替换子节点
44      * @param document
45      * @param newChild
46      * @param oldChild
47      */
48     public static void replaceNodeText(Node newChild,Node oldChild){
49         //oldChild替换替换为新的newChild节点
50         oldChild.getParentNode().replaceChild(newChild, oldChild);
51     }
52     /**
53      * 写入新节点
54      * @param document
55      * @param path
56      * @throws Exception
57      */
58     public static void write2Xml(Document document,String path) throws Exception{
59         //获取Transformer对象
60         Transformer transformer = TransformerFactory.newInstance().newTransformer();
61         //把写好的新的document树中写入新的文件(一般是覆盖原文件)
62         transformer.transform(new DOMSource(document), new StreamResult(path));
63     }
64 }

 

2、SAX解析

    SAX
      Simple API for XML
    开发包
      JAXP:是SUN公司推出的解析标准实现
      java API for xml Processing
    主要包含的类和接口
      org.w3c.dom:提供DOM方式解析XML的标准接口
      org.xml.sax:提供SAX方式解析XML的标准接口
      javax.xml:提供了解析XML文档的类

  (1)普通的解析方式

 1 package com.xujingyang.utils;
 2 
 3 
 4 import javax.xml.parsers.SAXParser;
 5 import javax.xml.parsers.SAXParserFactory;
 6 
 7 import org.xml.sax.Attributes;
 8 import org.xml.sax.SAXException;
 9 import org.xml.sax.helpers.DefaultHandler;
10 
11 public class saxDom {
12     public static void getDom(String XMLpath) throws Exception{
13         SAXParserFactory parserFactory = SAXParserFactory.newInstance();
14         SAXParser saxParser = parserFactory.newSAXParser();
15         saxParser.parse(XMLpath, new DefaultHandler(){
16             protected String result="";
17             @Override 
18             public void startDocument() throws SAXException {
19                 //开始解析文档
20                 super.startDocument();
21                 result+="document begin\r\n";
22             }
23 
24             @Override
25             public void startElement(String uri, String localName,
26                     String qName, Attributes attributes) throws SAXException {
27                 //开始解析节点
28                 super.startElement(uri, localName, qName, attributes);
29                 result+="\r\nelement begin";
30             }
31             @Override
32             public void characters(char[] ch, int start, int length)
33                     throws SAXException {
34                 //开始读取节点内容
35                 super.characters(ch, start, length);
36                 result+=String.copyValueOf(ch, start, length);
37             }
38 
39             @Override
40             public void endDocument() throws SAXException {
41                 //结束解析文档
42                 super.endDocument();
43                 result+="\r\ndocument end";
44                 System.out.println(result);
45             }
46 
47             @Override
48             public void endElement(String uri, String localName, String qName)
49                     throws SAXException {
50                 //结束解析节点
51                 super.endElement(uri, localName, qName);
52                 result+="\r\nelement end";
53             }
54         });
55     }
56     
57 }

  (2)封装JavaBean的解析方式

  

 1 package com.xujingyang.utils;
 2 
 3 
 4 import java.util.ArrayList;
 5 
 6 import javax.xml.parsers.SAXParser;
 7 import javax.xml.parsers.SAXParserFactory;
 8 
 9 import org.xml.sax.Attributes;
10 import org.xml.sax.SAXException;
11 import org.xml.sax.XMLReader;
12 import org.xml.sax.helpers.DefaultHandler;
13 
14 import com.xujingyang.domain.Book;
15 
16 public class sax4bean {
17     public static ArrayList<Book> getBooks() throws Exception{
18         //对象集合
19         final ArrayList<Book> books=new ArrayList<Book>();
20         SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
21         XMLReader reader = saxParser.getXMLReader();
22         reader.setContentHandler(new DefaultHandler(){
23             Book book=null;
24             String nodeString;//做判断是否节点是要找的属性节点
25 
26             @Override
27             public void startElement(String uri, String localName,
28                     String qName, Attributes attributes) throws SAXException {
29                 super.startElement(uri, localName, qName, attributes);
30                 //判断节点名称是要找的对象就初始化bean
31                 if("book".equals(qName)){
32                     book=new Book();
33                 }
34                 nodeString=qName;
35                 
36             }
37             @Override
38             public void characters(char[] ch, int start, int length)
39                     throws SAXException {
40                 super.characters(ch, start, length);
41                 if(book!=null){
42                     String textString=new String(ch, start, length);
43                     if("name".equals(nodeString)){
44                         book.setName(textString);
45                     }else if ("aothour".equals(nodeString)) {
46                         book.setAothour(textString);
47                     }else if ("price".equals(nodeString)) {
48                         book.setPrice(Float.parseFloat(textString));
49                     }
50                 }
51             }
52 
53 
54             @Override
55             public void endElement(String uri, String localName, String qName)
56                     throws SAXException {
57                 // TODO Auto-generated method stub
58                 super.endElement(uri, localName, qName);
59                 //每次节点解析结束就要判断是否是一个对象结束,如果结束就将对象置空
60                 if("book".equals(qName)){
61                     books.add(book);
62                     book=null;
63                 }
64                 //每次节点名称都要置空,否则就会读到空文本
65                 nodeString=null;
66             }
67         });
68         reader.parse("src/books.xml");
69         
70         return books;
71     }
72 }

  对象类

 1 package com.xujingyang.domain;
 2 
 3 public class Book {
 4     private String name;
 5     private String aothour;
 6     private float price;
 7     public String getName() {
 8         return name;
 9     }
10     public void setName(String name) {
11         this.name = name;
12     }
13     public String getAothour() {
14         return aothour;
15     }
16     public void setAothour(String aothour) {
17         this.aothour = aothour;
18     }
19     public float getPrice() {
20         return price;
21     }
22     public void setPrice(float price) {
23         this.price = price;
24     }
25     @Override
26     public String toString() {
27         return "Book [name=" + name + ", aothour=" + aothour + ", price="
28                 + price + "]";
29     }
30     
31 }

要解析的XML文档

 1 <?xml version="1.0" encoding="UTF-8" standalone="no"?><books>
 2     <book>
 3         <name>三国演义</name>
 4         <aothour>罗贯中</aothour>
 5         <price>22</price>
 6         
 7     </book>
 8     <book>
 9         <name>西游记</name>
10         <aothour>吴承恩</aothour>
11         <price>24</price>
12     </book>
13 </books>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值