使用 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}

在这个样本中,必须要注意以下几点:

  1. 使用 xmlStreamReader.getAttributeValue 是有效的,因为我们首先检查了解析器是否处于 START_ELEMENT 状态。在 evey 其他状态(ATTRIBUTES 除外)中,解析器被强制抛出 IllegalStateException,因为属性只能出现在元素的开头。

  2. 同样适用于 xmlStreamReader.getTextContent(),它的工作原理是因为我们处于知识中,我们在本文档中知道 <book> 元素没有非文本子节点。

对于更复杂的文档解析(更深层次,嵌套元素,…),将解析器委托给子方法或其他对象是一种很好的做法,例如有一个 BookParser 类或方法,并让它处理每个元素从 START_ELEMENT 到书籍 XML 标签的 END_ELEMENT。

人们还可以使用 Stack 对象来保持树上下的重要数据。