Java 如何使用XPath检查XML内容中是否存在节点?
Java 如何检查XML中是否存在某个属性?
要检查节点是否存在,我们可以执行 xpath 表达式并查看匹配的节点数量。
示例:
package com.onitroad.demo; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class XPathExample { public static void main(String[] args) throws Exception { // 从 XML 获取DOM String fileName = "employees.xml"; Document document = getDocument(fileName); String xpathExpression = ""; // 获取所有 employee的 firstName xpathExpression = "/employees/employee/firstName"; System.out.println(checkIfNodeExists(document, xpathExpression)); //true // 获取所有id xpathExpression = "/employees/employee/@id"; System.out.println(checkIfNodeExists(document, xpathExpression)); //true // 获取所有年龄 xpathExpression = "/employees/employee/@age"; System.out.println(checkIfNodeExists(document, xpathExpression)); //false // 获取所有部门 xpathExpression = "/employees/employee/department/name"; System.out.println(checkIfNodeExists(document, xpathExpression)); //true // 获取部门位置 xpathExpression = "/employees/employee/department/location"; System.out.println(checkIfNodeExists(document, xpathExpression)); //false } private static boolean checkIfNodeExists(Document document, String xpathExpression) throws Exception { boolean matches = false; // 创建 XPathFactory 对象 XPathFactory xpathFactory = XPathFactory.newInstance(); // 创建 XPath 对象 XPath xpath = xpathFactory.newXPath(); try { // 创建 XPathExpression 对象 XPathExpression expr = xpath.compile(xpathExpression); // 在XML文档上计算表达式结果 NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET); if(nodes != null && nodes.getLength() > 0) { matches = true; } } catch (XPathExpressionException e) { e.printStackTrace(); } return matches; } private static Document getDocument(String fileName) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(fileName); return doc; } }
日期:2020-09-17 00:10:12 来源:oir作者:oir