天天看點

解析XML封包--------DOM、JDOM、SAX

例:

<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
    <book id="1" name='book1'>
        <name>挪威的森林</name>
        <author>村上春樹</author>
        <year>2019</year>
        <price>89</price>
    </book>
    <book id="2" name='book2'>
        <name>設計模式</name>
        <year>2018</year>
        <price>386</price>
        <language>English</language>
    </book>    
</bookstore>
           

DOM文檔對象模型(10M文檔時記憶體溢出)

優點:

1、形成了樹結構,有助于更好的了解、掌握,且代碼容易編寫。

2、解析過程中,樹結構儲存在記憶體中,友善修改。

缺點:

1、由于檔案是一次性讀取,是以對記憶體的耗費比較大。

2、如果XML檔案比較大,容易影響解析性能且可能會造成記憶體溢出。

public static void main(String[] args) {
        //建立一個DocumentBuilderFactory的對象
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //建立一個DocumentBuilder的對象
        try {
            //建立DocumentBuilder對象
            DocumentBuilder db = dbf.newDocumentBuilder();
            //通過DocumentBuilder對象的parser方法加載data.xml檔案到目前項目下
            Document document = db.parse("src/com/xml/data.xml");
            //擷取所有book節點的集合
            NodeList bookList = document.getElementsByTagName("book");
            //通過nodelist的getLength()方法可以擷取bookList的長度
            System.out.println("book節點個數【" + bookList.getLength() + "】");
            //周遊每一個book節點
            for (int i = 0; i < bookList.getLength(); i++) {
                System.out.println("=================下面開始周遊第" + (i + 1) + "個節點=================");
                //通過 item(i)方法 擷取一個book節點,nodelist的索引值從0開始
                Node book = bookList.item(i);
                //擷取book節點的所有屬性集合
                NamedNodeMap attrs = book.getAttributes();
                //周遊book的屬性
                for (int j = 0; j < attrs.getLength(); j++) {
                    //通過item(index)方法擷取book節點的某一個屬性
                    Node attr = attrs.item(j);
                    //擷取屬性名
                    System.out.print("屬性名:" + attr.getNodeName());
                    //擷取屬性值
                    System.out.println("--屬性值" + attr.getNodeValue());
                }
                //解析book節點的子節點
                NodeList childNodes = book.getChildNodes();
                //周遊childNodes擷取每個節點的節點名和節點值
                for (int k = 0; k < childNodes.getLength(); k++) {
                    //區分出text類型的node以及element類型的node
                    if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
                        //擷取了element類型節點的節點名
                        System.out.println("第" + (k + 1) + "個節點的節點名:"+ childNodes.item(k).getNodeName());
                        //擷取了element類型節點的節點值
                        //System.out.println("--節點值是:" + childNodes.item(k).getTextContent());
                    }
                }
                System.out.println("======================結束周遊第" + (i + 1) + "個節點=================");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }        
    }
           

JDOM特征:(10M文檔時記憶體溢出)

1、僅使用具體類,而不使用接口。

2、API大量使用了Collections類。

private static ArrayList<Book> booksList = new ArrayList<Book>();

    public static void main(String[] args) {
        // 1.建立一個SAXBuilder的對象
        SAXBuilder saxBuilder = new SAXBuilder();
        InputStream in;
        try {
            // 2.建立一個輸入流,将xml檔案加載到輸入流中
            in = new FileInputStream("src/com/xml/data.xml");
            InputStreamReader isr = new InputStreamReader(in, "UTF-8");
            // 3.通過saxBuilder的build方法,将輸入流加載到saxBuilder中
            Document document = saxBuilder.build(isr);
            // 4.通過document對象擷取xml檔案的根節點
            Element rootElement = document.getRootElement();
            // 5.擷取根節點下的子節點的List集合
            List<Element> bookList = rootElement.getChildren();
            // 繼續進行解析
            for (Element book : bookList) {
                Book bookEntity = new Book();
                System.out.println("======開始解析第" + (bookList.indexOf(book) + 1)
                        + "書======");
                // 解析book的屬性集合
                List<Attribute> attrList = book.getAttributes();
                // //知道節點下屬性名稱時,擷取節點值
                // book.getAttributeValue("id");
                // 周遊attrList(針對不清楚book節點下屬性的名字及數量)
                for (Attribute attr : attrList) {
                    // 擷取屬性名
                    String attrName = attr.getName();
                    // 擷取屬性值
                    String attrValue = attr.getValue();
                    System.out.println("屬性名:" + attrName + "----屬性值:"
                            + attrValue);
                    if (attrName.equals("id")) {
                        bookEntity.setId(attrValue);
                    }
                }
                // 對book節點的子節點的節點名以及節點值的周遊
                List<Element> bookChilds = book.getChildren();
                for (Element child : bookChilds) {
                    System.out.println("節點名:" + child.getName() + "----節點值:"
                            + child.getValue());
                    if (child.getName().equals("name")) {
                        bookEntity.setName(child.getValue());
                    }
                    else if (child.getName().equals("author")) {
                        bookEntity.setAuthor(child.getValue());
                    }
                    else if (child.getName().equals("year")) {
                        bookEntity.setYear(child.getValue());
                    }
                    else if (child.getName().equals("price")) {
                        bookEntity.setPrice(child.getValue());
                    }
                    else if (child.getName().equals("language")) {
                        bookEntity.setLanguage(child.getValue());
                    }
                }
                System.out.println("======結束解析第" + (bookList.indexOf(book) + 1)+ "書======");
                booksList.add(bookEntity);
                bookEntity = null;
                System.out.println(booksList.size());
                System.out.println(booksList.get(0).getId());
                System.out.println(booksList.get(0).getName());
                
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
           

XML簡單應用程式接口

優點:

1、采用事件驅動模式,對記憶體耗費比較小。 

2、适用于隻處理XML檔案中的資料時。

缺點:

1、編碼比較麻煩。

2、很難同時通路XML檔案中的多處不同資料。

SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
            SAXParser parser = factory.newSAXParser();
            SAXParserHandler handler = new SAXParserHandler();
            parser.parse("src/com/xml/data.xml", handler);
            System.out.println("~!~!~!共有" + handler.getBookList().size() + "本書");
            for (Book book : handler.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(book.getLanguage());
                System.out.println("----finish----");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
           
String value = null;
	Book book = null;
	private ArrayList<Book> bookList = new ArrayList<Book>();
	public ArrayList<Book> getBookList() {
		return bookList;
	}
	int bookIndex = 0;
	/**
	 * 用來辨別解析開始
	 */
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		System.out.println("SAX解析開始");
	}
	/**
	 * 用來辨別解析結束
	 */
	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
		System.out.println("SAX解析結束");
	}
	/**
	 * 解析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")) {
			bookIndex++;
			//建立一個book對象
			book = new Book();
			//開始解析book元素的屬性
			System.out.println("======================開始周遊某一本書的内容=================");
			//不知道book元素下屬性的名稱以及個數,如何擷取屬性名以及屬性值
			int num = attributes.getLength();
			for(int i = 0; i < num; 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("name") && !qName.equals("bookstore")) {
			System.out.print("節點名是:" + qName + "---");
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		//調用DefaultHandler類的endElement方法
		super.endElement(uri, localName, qName);
		//判斷是否針對一本書已經周遊結束
		if (qName.equals("book")) {
			bookList.add(book);
			book = null;
			System.out.println("======================結束周遊某一本書的内容=================");
		}
		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);
		}
		else if (qName.equals("language")) {
			book.setLanguage(value);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)throws SAXException {
		// TODO Auto-generated method stub
		super.characters(ch, start, length);
		value = new String(ch, start, length);
		if (!value.trim().equals("")) {
			System.out.println("節點值是:" + value);
		}
	}