Java xpath check if xml tag exists

To check if an XML tag exists using XPath in Java, you can use the javax.xml.xpath package. Here's an example that demonstrates how to check if a tag exists in an XML document using XPath:

refer to:‮i‬giftidea.com
import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

public class XPathTagExistenceChecker {

    public static void main(String[] args) throws Exception {
        // create an XML document string
        String xml = "<root><child attribute=\"value\">text</child></root>";

        // create an XPath expression to select the tag
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        XPathExpression expr = xpath.compile("/root/child");

        // parse the XML document
        InputSource inputSource = new InputSource(new StringReader(xml));

        // evaluate the XPath expression
        Object result = expr.evaluate(inputSource, javax.xml.xpath.XPathConstants.NODE);

        // check if the tag exists
        if (result == null) {
            System.out.println("Tag does not exist.");
        } else {
            System.out.println("Tag exists.");
        }
    }

}

This code creates an XML document string, and then creates an XPath expression that selects the child element. The XPath expression is compiled and then evaluated against the XML document using the evaluate method of the XPathExpression object. The evaluate method is called with the XPathConstants.NODE constant as the second argument, which tells the method to return a org.w3c.dom.Node object that represents the selected node. If the tag exists, the Node object is returned; otherwise, null is returned.

After evaluating the XPath expression, the code checks if the Node object is null, which indicates that the tag does not exist. If the Node object is not null, the tag exists.