简体   繁体   中英

XML Parsing from Java Rest Service Response

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>

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());
        }
    } 

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

eg

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'
}

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM