How can I retrieve a node based on its name using dom4j?
To locate a node based on its node name, you can use an XPath expression. This functionality can be easily implemented using the dom4j library. Here is an example code:
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import java.util.List;
public class Dom4jExample {
public static void main(String[] args) {
try {
SAXReader reader = new SAXReader();
Document document = reader.read("example.xml");
String nodeName = "book"; // 要获取的节点名称
// 使用XPath表达式定位节点
XPath xPath = document.createXPath("//" + nodeName);
List<Node> nodes = xPath.selectNodes(document);
for (Node node : nodes) {
Element element = (Element) node;
System.out.println(element.asXML()); // 输出节点内容
}
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
In the example above, we start by creating a SAXReader object to read an XML file, then use an XPath expression (“//” + nodeName) to locate all nodes with the name “book” and print their content. You can adjust the node name and XML file path as needed.