Java XPathでリスト取得!最適な方法を解説
XPathを使用してリストを取得するJavaの方法は、XPath式を使用して要素を選択し、それをNodeListオブジェクトに格納することです。以下は簡単なサンプルコードです:
import javax.xml.xpath.*;
import org.w3c.dom.*;
public class XPathExample {
public static void main(String[] args) {
try {
// 创建 XPath 对象
XPath xPath = XPathFactory.newInstance().newXPath();
// 编译 XPath 表达式
XPathExpression expression = xPath.compile("//book");
// 获取 XML 文档
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("books.xml");
// 在文档上应用 XPath 表达式
NodeList nodeList = (NodeList) expression.evaluate(document, XPathConstants.NODESET);
// 遍历 NodeList
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
System.out.println(node.getNodeName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上記の例では、XPath式//bookを使用して文書内のすべてのbook要素を選択し、それらをNodeListオブジェクトに保存しました。その後、NodeListを反復処理し、各要素のノード名を出力しました。XML文書のパスとXPath式を自分のニーズに合わせて置換する必要があることに注意してください。