-1

I am getting the below XML response from Java Rest Service.Could any one how to get status tag information?

<operation name="EDIT_REQUEST">
<result>
<status>Failed</status>
<message>Error when editing request details - Request Closing Rule Violation. Request cannot be Resolved</message>
</result>
</operation>
String
  • 3,660
  • 10
  • 43
  • 66

4 Answers4

1

A rough code is here

    ByteArrayInputStream input =  new ByteArrayInputStream(
            response.getBytes("UTF-8"));

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(input);

    // first get root tag and than result tag and childs of result tag
    NodeList childNodes = doc.getDocumentElement().getChildNodes().item(0).getChildNodes();
    for(int i = 0 ; i < childNodes.getLength(); i++){
        if("status".equals(childNodes.item(i).getNodeName())){
            System.out.println(childNodes.item(i).getTextContent());
        }
    } 
Naveen Ramawat
  • 1,425
  • 1
  • 15
  • 27
1

If you are just concerned with the status text, how about just having a simple regex with a group?

e.g.

String responseXml = 'xml response from service....'

Pattern p = Pattern.compile("<status>(.+?)</status>");
Matcher m = p.matcher(responseXml);

if(m.find())
{
   System.out.println(m.group(1)); //Should print 'Failed'
}
sarumait
  • 66
  • 4
1

XPath is a very robust and intuitive way to quickly query XML documents. You can reach value of status tag by following steps.

   DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
   documentBuilderFactory.setNamespaceAware(true);
   DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
   Document doc = builder.parse(stream); //input stream of response.

   XPathFactory xPathFactory = XPathFactory.newInstance();
   XPath xpath = xPathFactory.newXPath();

   XPathExpression expr = xpath.compile("//status"); // Look for status tag value.
   String status =  expr.evaluate(doc);
   System.out.println(status);
ring bearer
  • 20,383
  • 7
  • 59
  • 72
-1

One option is to use the library, imported using , like:

compile 'org.jooq:joox:1.3.0'

And use it like:

import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import static org.joox.JOOX.$;

public class Main {

    public static void main(String[] args) throws IOException, SAXException {
        System.out.println(
                $(new File(args[0])).xpath("/operation/result/status").text()
        );
    }
}

It yields:

Failed
Birei
  • 35,723
  • 2
  • 77
  • 82
  • 1
    This is not a gradle question, and there is no reason to add the burden of a third-party library to do something that can easily be done in with regular Java SE. – VGR Jul 06 '15 at 13:49