Return a string value based on XPATH condition

后端 未结 2 846
被撕碎了的回忆
被撕碎了的回忆 2020-12-09 11:34

If I have the below XML, how to specify a xpath to return a string based on a condition. For example here if //b[@id=23] then \"Profit\" else \"Loss\"



        
2条回答
  •  情话喂你
    2020-12-09 11:56

    You can't; you'd have to use XQuery for this. see e.g. XQuery Conditional Expressions

    Or, if the resulting string is only used within Java, you can just process the value returned by XPath within your Java code:

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//b[@id=23]");
    boolean result = expr.evaluate(doc, XPathConstants.BOOLEAN);
    
    if (result) return "Profit";
    else return "Loss";
    

提交回复
热议问题