How to check if an element exists in the xml using xpath?

后端 未结 6 1198
野性不改
野性不改 2020-12-08 18:47

Below is my element hierarchy. How to check (using xpath) that AttachedXml element is present under CreditReport of Primary

6条回答
  •  臣服心动
    2020-12-08 18:59

    The Saxon documentation, though a little unclear, seems to suggest that the JAXP XPath API will return false when evaluating an XPath expression if no matching nodes are found.

    This IBM article mentions a return value of null when no nodes are matched.

    You might need to play around with the return types a bit based on this API, but the basic idea is that you just run a normal XPath and check whether the result is a node / false / null / etc.

    XPathFactory xpathFactory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
    XPath xpath = xpathFactory.newXPath();
    XPathExpression expr = xpath.compile("/Consumers/Consumer/DataSources/Credit/CreditReport/AttachedXml");
    Object result = expr.evaluate(doc, XPathConstants.NODE);
    
    if ( result == null ) {
        // do something
    }
    

提交回复
热议问题