1. 程式人生 > >XML之StAX(二)

XML之StAX(二)

面向Stream的StAX

XMLStreamReader

StAX中的XMLStreamReader類提供了一個Cursor形式的API,用於解析XML。和Iterator API一樣,允許你確定何時訪問下一個Event,這裡的Event是元素開頭,元素的結尾,一組text等。XMLStreamReader的next()方法不返回Events,而是移動Cursor到下一個XML的Event。你可以直接呼叫方法獲取當前Event的更多資訊,這和你迭代JDBC ResultSet的記錄一樣。下面是你可能遇到的XML Stream的Events,它們包含在javax.xml.stream.XMLStreamConstants:

  1. ATTRIBUTE
  2. CDATA
  3. CHARACTERS
  4. COMMENT
  5. DTD
  6. END_DOCUMENT
  7. END_ELEMENT
  8. ENTITY_DECLARATION
  9. ENTITY_REFERENCE
  10. NAMESPACE
  11. NOTATION_DECLARATION
  12. PROCESSING_INSTRUCTION
  13. SPACE
  14. START_DOCUMENT
  15. START_ELEMENT

下面是一個簡單的例子:

public static void read()throws IOException{
	XMLInputFactory factory = XMLInputFactory.newFactory();
	Reader reader = null;

	try {
//            reader = new FileReader("F:\\Codes\\IDEA\\Tools\\data\\xml\\test.xml");
		InputStream input = CursorAccess.class.getClassLoader().getResourceAsStream("test.xml");
		XMLStreamReader streamReader = factory.createXMLStreamReader(input);
		while (streamReader.hasNext()){
			int type = streamReader.next();

		  // streamReader.getEventType() == XMLStreamReader.START_ELEMENT == XMLStreamConstans.START_ELEMENT
		  // equals streamReader.isStartElement() and type==XMLStreamConstans.START_ELEMENT
			if(streamReader.isStartElement()){
				QName element = streamReader.getName();
				String name = element.toString();
				//
				if(name.equals("book")) {
					QName attrName = streamReader.getAttributeName(0);
					String attrValue = streamReader.getAttributeValue(0);
					System.out.println(element + ": " + attrName + "=" + attrValue);
				}

				else if(!name.equals("bookstore") && !name.equals("book")){
					String value = streamReader.getElementText();
					System.out.println(element + ": " + value);
				}
			}
		}
	}
	catch (Exception e){
		e.printStackTrace();
	}
	finally {
		if(reader != null) {
			reader.close();
		}
	}
}


和XMLEventReader一樣,XMLStreamReader也可以自定義Filter:

public static void readFilter()throws IOException{
	XMLInputFactory factory = XMLInputFactory.newFactory();
	InputStream input = null;

	try {
		input = new FileInputStream(new File("F:\\Codes\\IDEA\\Tools\\data\\xml\\test.xml"));
		XMLStreamReader streamReader = factory.createFilteredReader(
				factory.createXMLStreamReader(input), new StreamFilter() {
					@Override
					public boolean accept(XMLStreamReader reader) {
						if(reader.isStartElement()){
							String name = reader.getName().toString();
							if(name.equals("title") || name.equals("price")){
								return true;
							}
						}
						return false;
					}
				});

		while (streamReader.hasNext()){
			streamReader.next();

			if(streamReader.isStartElement()){
				String name = streamReader.getLocalName();
				System.out.println(name + ": " + streamReader.getElementText());
			}
		}
	}
	catch (Exception e){
		e.printStackTrace();
	}
	finally {
		if(input != null){
			input.close();
		}
	}
}

XMLStreamWriter

XMLStreamWriter是用於生成XML的,不過不同於XMLEventWriter的是,它不要求為元素定義字首:

public static void write(){
	XMLOutputFactory factory = XMLOutputFactory.newFactory();

	try {
		XMLStreamWriter writer = factory.createXMLStreamWriter(
				new FileWriter("F:\\Codes\\IDEA\\Tools\\data\\xml\\cursor.xml"));

		writer.writeStartDocument();
		writer.writeStartElement("test:bookstore");

		writer.writeStartElement("test:book");
		writer.writeAttribute("category", "COMPUTER");
		writer.writeStartElement("author");
		writer.writeCharacters("Giada De Laurentiis");
		writer.writeEndElement();
		writer.writeEndElement();
		writer.writeEndElement();
		writer.writeEndDocument();

		writer.flush();
		writer.close();
	}
	catch (Exception e){
		e.printStackTrace();
	}
}

參考文獻: