JAXPとは、Java用のXML APIです。
| 特徴 | StAX | SAX | DOM | TrAX |
|---|---|---|---|---|
| APIの種類 | Pull, streaming | Push, streaming | In memory tree | XSLT Rule |
| 使いやすさ | ○ | × | ○ | × |
| XPath対応 | × | × | ○ | ○ |
| CPUとメモリの使用効率 | ○ | ○ | × | × |
| 直接アクセス | × | × | ○ | ○ |
| XMLの読み込み | ○ | ○ | ○ | ○ |
| XMLの書き込み | ○ | × | ○ | ○ |
| 作成、読み込み、更新、削除 | × | × | ○ | × |
たとえば、
<?xml version="1.0" encoding="UTF-8"?> <foo>SAMPLE</foo>
というファイル (sample.xml) があるとき、これをDOMで処理するには次のようにします。
File file = new File("sample.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(file); // [#document: null]
Element root = document.getDocumentElement(); // [foo: null]
Node node = root.getFirstChild(); // [#text: SAMPLE]
System.out.println(node.getNodeValue()); // SAMPLE
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}