JDOM 核心類
SAXBuilder:構建 Document 對象
Document:文檔根節點
Element:元素節點,提供 getChildren()、getAttributeValue()
示例 XML (mystruts.xml)
解析代碼
public class JdomReadXml {
public static void main(String[] args) {
SAXBuilder sax = new SAXBuilder();
try {
Document doc = sax.build(new File("mystruts.xml"));
Element root = doc.getRootElement();
List actions = root.getChildren("action");
for (Element action : actions) {
System.out.println(action.getAttributeValue("path"));
System.out.println(action.getAttributeValue("class"));
List forwards = action.getChildren("forward");
for (Element forward : forwards) {
System.out.println(forward.getAttributeValue("name"));
System.out.println(forward.getAttributeValue("url"));
}
}
} catch (JDOMException | IOException e) { e.printStackTrace(); }
}
}
輸出結果
/test
com.demo.LoginAction
success
test.jsp
failure
failure.jsp
/user
com.demo.UserAction
success
test.jsp
failure
failure.jsp
JDOM vs DOM vs SAX
| 解析器 | 模型 | 內存 | 速度 | 易用性 |
| DOM | 樹模型 | 高 | 中 | 高 |
| SAX | 事件流 | 低 | 快 | 低 |
| JDOM | 樹模型 | 中 | 中 | 最高(Java 原生 API) |
常用操作速查
- 獲取屬性:
element.getAttributeValue("name")
- 獲取子元素:
element.getChildren("tag") 或 element.getChild("tag")
- 獲取文本:
element.getText() / element.getTextTrim()
- 創建元素:
new Element("tag")
- 輸出 XML:
XMLOutputter.output(doc, outputStream)