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解析和操作。