dom4j是一個Java的XML解析庫,可以用于讀取、創建和修改XML文檔。下面是dom4j的一些常用用法:
SAXReader reader = new SAXReader();
Document document = reader.read(new File("path/to/xml/file.xml"));
// 使用XPath表達式
List<Node> nodes = document.selectNodes("//book");
for (Node node : nodes) {
// 處理節點
System.out.println(node.getName());
}
// 使用迭代器
Iterator<Element> iterator = document.getRootElement().elementIterator();
while (iterator.hasNext()) {
Element element = iterator.next();
// 處理節點
System.out.println(element.getName());
}
Element titleElement = (Element) document.selectSingleNode("//title");
String title = titleElement.getText();
Element authorElement = (Element) document.selectSingleNode("//author");
String author = authorElement.attributeValue("name");
Element bookElement = document.addElement("book");
Element titleElement = bookElement.addElement("title");
titleElement.setText("Java Programming");
Element authorElement = bookElement.addElement("author");
authorElement.addAttribute("name", "John Doe");
Element titleElement = (Element) document.selectSingleNode("//title");
titleElement.setText("New Title");
Element authorElement = (Element) document.selectSingleNode("//author");
authorElement.addAttribute("name", "Jane Smith");
Element authorElement = (Element) document.selectSingleNode("//author");
Element parentElement = authorElement.getParent();
parentElement.remove(authorElement);
以上就是dom4j的一些常用用法,可以根據具體需求選擇合適的方法進行XML解析和操作。