1. 程式人生 > >建立XML(2/4)--通過SAX方式

建立XML(2/4)--通過SAX方式

注:生成如下內容XML

<?xml version="1.0" encoding="UTF-8"?>
<bookStore>
	<book id="1">
		<name>冰與火之歌</name>
		<author>喬治馬丁</author>
		<year>2014</year>
		<price>88</price>
	</book>
	<book id="2">
		<name>安徒生童話</name>
		<author>丹麥</author>
		<year>2004</year>
		<price>66</price>
	</book>
	<book id="3">
		<name>java開發</name>
		<author>美國</author>
		<year>2000</year>
		<price>99</price>
	</book>
</bookStore>

  • 一、準備工作

建立工廠物件 + 設定XML文件格式 + 建立Result物件
  • 二、生成子節點+節點屬性

//開始新增節點
handler.startElement("", "", "bookStore", attr);
//新增子節點bookStores-book以及屬性值
attr.addAttribute("", "", "id", "", "1");
handler.startElement("", "", "book", attr);
//結束子節點bookStores-book
handler.endElement("", "", "book");
  • 三、生成帶文字的子節點

//這裡建立的屬性以及值都是從books.xml中獲取到的
if (book.getName() != null && !book.getName().trim().equals("")) {
    attr.clear();
    handler.startElement("", "", "name", attr);
    //新增name的文字值
    handler.characters(book.getName().toCharArray(), 0, book.getName().length());
    //結束子節點bookStores-book-name
    handler.endElement("", "", "name");
}

  1. 程式碼1、SAXTest.java  (建立+解析XML)
    package com.test.saxtest;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Result;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerConfigurationException;
    import javax.xml.transform.sax.SAXTransformerFactory;
    import javax.xml.transform.sax.TransformerHandler;
    import javax.xml.transform.stream.StreamResult;
    
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.AttributesImpl;
    
    import com.cisau.entity.Book;
    import com.cisau.handler.SAXParserHandler;
    
    public class SAXTest {
    	
    	public static void main(String[] args) {
    		SAXTest saxTest = new SAXTest();
    		saxTest.createXML();
    	}
    	
    	/**
    	 * 解析XML
    	 */
    	public ArrayList<Book> parseXML() {
    		//1、建立SAXParserFactory物件
    				SAXParserFactory saxpf = SAXParserFactory.newInstance();
    				SAXParserHandler saxParserHandler = null;
    				try {
    				//2、通過SAXParserFactory建立SAXParser的例項
    				SAXParser parser = saxpf.newSAXParser();
    				//3、建立SAXParserHandler物件
    				saxParserHandler = new SAXParserHandler();
    				parser.parse("books.xml", saxParserHandler);
    				
    				//new-start
    				System.out.println("%%%%%%%%%%%共有" + saxParserHandler.getBookList().size() + "本書");
    				for (Book book : saxParserHandler.getBookList()) {
    					System.out.println(book.getId());
    					System.out.println(book.getName());
    					System.out.println(book.getAuthor());
    					System.out.println(book.getYear());
    					System.out.println(book.getPrice());
    					System.out.println("---------finish  -------------");
    				}
    				//new-over
    				
    				}catch (IOException e) {
    					e.printStackTrace();
    				} catch (ParserConfigurationException e) {
    					e.printStackTrace();
    				} catch (SAXException e) {
    					e.printStackTrace();
    				}
    				return saxParserHandler.getBookList();
    	}//parseXML()
    
    
    	/**
    	 * 建立XML
    	 */
    	public void createXML() {
    		ArrayList<Book> bookList = parseXML();
    		//1、建立TransformerFactory物件
    		SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    		try {
    			//2、通過SAXTransformerFactory物件建立一個TransformerHandler物件
    			TransformerHandler handler = factory.newTransformerHandler();
    			//3、通過TransformerHandler物件建立一個Transformer
    			Transformer transformer = handler.getTransformer();
    			//4、通過Transformer物件對生成的XML檔案格式進行設定
    				//設定編碼格式
    				transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    				//設定XML"是否換行"
    				transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    			//5、建立一個Result物件
    				File file = new File("src/res/newbooks.xml");
    				if (!file.exists()) {
    					file.createNewFile();
    				}
    			//6、建立Result物件,並且使其與handler關聯
    			Result result = new StreamResult(new FileOutputStream(file));
    			handler.setResult(result);
    			//7、通過handler進行XML檔案的寫入
    				//開啟文件
    				handler.startDocument();
    				AttributesImpl attr = new AttributesImpl();
    					//開始新增節點
    					handler.startElement("", "", "bookStore", attr);
    						/*//新增子節點bookStores-book
    						attr.clear();
    						attr.addAttribute("", "", "id", "", "1");
    						handler.startElement("", "", "book", attr);
    						//結束子節點bookStores-book
    						handler.endElement("", "", "book");*/
    						for (Book book : bookList) {
    							//新增子節點bookStores-book以及他的屬性
    								attr.clear();
    								attr.addAttribute("", "", "id", "", book.getId());
    								handler.startElement("", "", "book", attr);
    							
    								//<1>新增子節點bookStores-book-name
    					//這裡建立的屬性以及值都是從books.xml中獲取到的
    								if (book.getName() != null && !book.getName().trim().equals("")) {
    									attr.clear();
    									handler.startElement("", "", "name", attr);
    									//新增name的文字值
    									handler.characters(book.getName().toCharArray(), 0, book.getName().length());
    									//結束子節點bookStores-book-name
    									handler.endElement("", "", "name");
    								}
    								//<2>新增子節點bookStores-book-author
    								if (book.getAuthor() != null && !book.getAuthor().trim().equals("")) {
    									attr.clear();
    									handler.startElement("", "", "author", attr);
    									//新增author的文字值
    									handler.characters(book.getAuthor().toCharArray(), 0, book.getAuthor().length());
    									//結束子節點bookStores-book-author
    									handler.endElement("", "", "author");
    								}
    								//<3>新增子節點bookStores-book-year
    								if (book.getYear() != null && !book.getYear().trim().equals("")) {
    									attr.clear();
    									handler.startElement("", "", "year", attr);
    									//新增year的文字值
    									handler.characters(book.getYear().toCharArray(), 0, book.getYear().length());
    									//結束子節點bookStores-book-year
    									handler.endElement("", "", "year");
    								}
    								//<4>新增子節點bookStores-book-price
    								if (book.getPrice() != null && !book.getPrice().trim().equals("")) {
    									attr.clear();
    									handler.startElement("", "", "price", attr);
    									//新增price的文字值
    									handler.characters(book.getPrice().toCharArray(), 0, book.getPrice().length());
    									//結束子節點bookStores-book-price
    									handler.endElement("", "", "price");
    								}
    							
    							//結束子節點bookStores-book
    							handler.endElement("", "", "book");
    						}
    					//結束新增節點
    					handler.endElement("", "", "bookStore");
    				//結束文件
    				handler.endDocument();
    				System.out.println("生成完畢...");
    		} catch (TransformerConfigurationException e) {
    			e.printStackTrace();
    		}catch (FileNotFoundException e) {
    			e.printStackTrace();
    		}catch (IOException e) {
    			e.printStackTrace();
    		}catch (SAXException e) {
    			e.printStackTrace();
    		}
    	}
    }
    

     

  2. SAXParserHandler.java
    package com.cisau.handler;
    
    import java.util.ArrayList;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    import com.cisau.entity.Book;
    
    public class SAXParserHandler extends DefaultHandler {
    	int bookIndex = 0;
    	String value = null;
    	Book book = null;
    	private ArrayList<Book> bookList = new ArrayList<Book>();
    	
    	public ArrayList<Book> getBookList() {
    		return bookList;
    	} 
    
    	//******************************************************************************************
    	/**
    	 * 遍歷XML檔案的--開始--標籤
    	 * 解析XML元素
    	 */
    	@Override
    	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    		//呼叫DefaultHandler的startElement方法
    		super.startElement(uri, localName, qName, attributes);
    		if (qName.equals("book")) {
    			//建立一個bookd物件
    					book = new Book();
    			bookIndex ++ ;
    			System.out.println("=============開始遍歷" + bookIndex + "本書的內容============");
    			//已知book標籤中只有一個ID屬性,根據屬性名獲取屬性值
    /*			String value = attributes.getValue("id");
    			System.out.println("book標籤中的屬性值是:" + value);*/
    			//不知道book標籤中的屬性名和個數
    			int length = attributes.getLength();
    			for (int i = 0; i < length; i++) {
    				System.out.print("book元素的第" + (i+1) + "個屬性名是:" + attributes.getQName(i));
    				System.out.println("-----屬性值是:" + attributes.getValue(i));
    						if (attributes.getQName(i).equals("id")) {
    							book.setId(attributes.getValue(i));
    						}
    			}
    		}
    		else if(!qName.equals("bookstore")){
    			System.out.print("節點名是:" + qName + "--------");
    		}
    	}
    	
    	/**
    	 * 遍歷XML檔案的--結束--標籤
    	 */
    	@Override
    	public void endElement(String uri, String localName, String qName) throws SAXException {
    		//呼叫DefaultHandler的startElement方法
    		super.endElement(uri, localName, qName);
    		if (qName.equals("book")) {
    			bookList.add(book);
    			book = null;
    			System.out.println("=============結束遍歷" + bookIndex + "本書的內容============");
    		}else if (qName.equals("name")) {
    			book.setName(value);
    		}else if (qName.equals("author")) {
    			book.setAuthor(value);
    		}else if (qName.equals("year")) {
    			book.setYear(value);
    		}else if (qName.equals("price")) {
    			book.setPrice(value);
    		}
    		
    	}
    	
    	//***************************************標識開始解析***************************************************
    	
    	/**
    	 * 標識XML解析--開始
    	 */
    	@Override
    	public void startDocument() throws SAXException {
    		super.startDocument();
    		System.out.println("解析:開始--");
    	}
    	
    	/**
    	 * 標識XML解析--結束
    	 */
    	@Override
    	public void endDocument() throws SAXException {
    		super.endDocument();
    		System.out.println("解析:--結束");
    	}
    	
    	//****************************************開始獲取節點資訊**************************************************
    	
    	/**
    	 * 獲取整個文件中的所有內容---解析節點名+節點間文字
    	 */
    	@Override
    	public void characters(char[] ch, int start, int length) throws SAXException {
    		super.characters(ch, start, length);
    		value = new String(ch, start, length);
    		if (!value.trim().equals("")) {
    			System.out.println("節點值是:" + value);
    		}
    		
    	}
    }
    

     

  3. Book.java
    package com.cisau.entity;
    
    public class Book {
    	private String id;
    	private String name;
    	private String author;
    	private String year;
    	private String price;
    	private String language;
    ----------------------------------------
        get()+set()方法
    }
    

     

  4. books.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <bookstore>
    	<book id="1">
    		<name>冰與火之歌</name>
    		<author>喬治馬丁</author>
    		<year>2014</year>
    		<price>88</price>
    	</book>
    	
    	<book id ="2">
    		<name>安徒生童話</name>
    		<author>丹麥</author>
    		<year>2004</year>
    		<price>66</price>
    	</book>
    	
    	<book id="3">
    			<name>java開發</name>
    			<author>美國</author>
    			<year>2000</year>
    			<price>99</price>
    	</book>
    </bookstore>