dom4jでノードの名前に基づいてノードを取得する方法は何ですか?
ノード名に基づいてノードを取得するには、XPath式を使用してノードを特定できます。 dom4jライブラリを使用すると、この機能を簡単に実現できます。以下はサンプルコードです:
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();
}
}
}
上記の例では、まずSAXReaderオブジェクトを作成してXMLファイルを読み取り、次にXPath式(「//」+ノード名)を使用して「book」という名前のすべてのノードを特定し、ノードの内容をプリントアウトします。ノード名やXMLファイルのパスを必要に応じて変更することができます。