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\"
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";