使用 StAX API 解析文件
考慮以下檔案:
<?xml version='1.0' encoding='UTF-8' ?>
<library>
<book id='1'>Effective Java</book>
<book id='2'>Java Concurrency In Practice</book>
<notABook id='3'>This is not a book element</notABook>
</library>
可以使用以下程式碼來解析它並按書 ID 構建書名的地圖。
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
public class StaxDemo {
public static void main(String[] args) throws Exception {
String xmlDocument = "<?xml version='1.0' encoding='UTF-8' ?>"
+ "<library>"
+ "<book id='1'>Effective Java</book>"
+ "<book id='2'>Java Concurrency In Practice</book>"
+ "<notABook id='3'>This is not a book element </notABook>"
+ "</library>";
XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
// Various flavors are possible, e.g. from an InputStream, a Source, ...
XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(xmlDocument));
Map<Integer, String> bookTitlesById = new HashMap<>();
// We go through each event using a loop
while (xmlStreamReader.hasNext()) {
switch (xmlStreamReader.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
System.out.println("Found start of element: " + xmlStreamReader.getLocalName());
// Check if we are at the start of a <book> element
if ("book".equals(xmlStreamReader.getLocalName())) {
int bookId = Integer.parseInt(xmlStreamReader.getAttributeValue("", "id"));
String bookTitle = xmlStreamReader.getElementText();
bookTitlesById.put(bookId, bookTitle);
}
break;
// A bunch of other things are possible : comments, processing instructions, Whitespace...
default:
break;
}
xmlStreamReader.next();
}
System.out.println(bookTitlesById);
}
這輸出:
Found start of element: library
Found start of element: book
Found start of element: book
Found start of element: notABook
{1=Effective Java, 2=Java Concurrency In Practice}
在這個樣本中,必須要注意以下幾點:
-
使用
xmlStreamReader.getAttributeValue
是有效的,因為我們首先檢查瞭解析器是否處於START_ELEMENT
狀態。在 evey 其他狀態(ATTRIBUTES
除外)中,解析器被強制丟擲IllegalStateException
,因為屬性只能出現在元素的開頭。 -
同樣適用於
xmlStreamReader.getTextContent()
,它的工作原理是因為我們處於知識中,我們在本文件中知道<book>
元素沒有非文字子節點。
對於更復雜的文件解析(更深層次,巢狀元素,…),將解析器委託給子方法或其他物件是一種很好的做法,例如有一個 BookParser
類或方法,並讓它處理每個元素從 START_ELEMENT 到書籍 XML 標籤的 END_ELEMENT。
人們還可以使用 Stack
物件來保持樹上下的重要資料。