使用 XPath 在给定 XML 内容中检查节点是否存在或在 XML 中检查属性是否存在的 Java 示例。
要验证节点或标记是否存在于 XML 内容中,您可以针对该 XML 的 DOM 文档执行 xpath 表达式并计算匹配的节点。
matching nodes > zero
– 存在 XML 标记/属性。matching nodes <= zero
– XML 标签/属性不存在。<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employees> <employee id="1"> <firstName>Lokesh</firstName> <lastName>Gupta</lastName> <department> <id>101</id> <name>IT</name> </department> </employee> <employee id="2"> <firstName>Brian</firstName> <lastName>Schultz</lastName> <department> <id>102</id> <name>HR</name> </department> </employee> </employees>
package com.cundage.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 { // Get DOM Node for XML String fileName = "employees.xml"; Document document = getDocument(fileName); String xpathExpression = ""; // Get all employee names xpathExpression = "/employees/employee/firstName"; System.out.println(checkIfNodeExists(document, xpathExpression)); //true // Get all employee ids xpathExpression = "/employees/employee/@id"; System.out.println(checkIfNodeExists(document, xpathExpression)); //true // Get all employee age xpathExpression = "/employees/employee/@age"; System.out.println(checkIfNodeExists(document, xpathExpression)); //false // Get all department names xpathExpression = "/employees/employee/department/name"; System.out.println(checkIfNodeExists(document, xpathExpression)); //true // Get department locations 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; // Create XPathFactory object XPathFactory xpathFactory = XPathFactory.newInstance(); // Create XPath object XPath xpath = xpathFactory.newXPath(); try { // Create XPathExpression object XPathExpression expr = xpath.compile(xpathExpression); // Evaluate expression result on XML document 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; } }
程序输出:
true true false true false
更多参考:Xpath 示例
快乐学习!!
地址:https://www.cundage.com/article/xpath-check-if-xml-tag-exists.html