11

Hello I am getting back a string from a webservice.

I need to parse this string and get the text in error message?

My string looks like this:

<response>
<returnCode>-2</returnCode>
<error>
<errorCode>100</errorCode>
<errorMessage>ERROR HERE!!!</errorMessage>
</error>
</response>

Is it better to just parse the string or convert to xml then parse?

user987339
  • 10,519
  • 8
  • 40
  • 45
Doc Holiday
  • 9,928
  • 32
  • 98
  • 151

3 Answers3

16

I'd use Java's XML document libraries. It's a bit of a mess, but works.

String xml = "<response>\n" +
             "<returnCode>-2</returnCode>\n" +
             "<error>\n" +
             "<errorCode>100</errorCode>\n" +
             "<errorMessage>ERROR HERE!!!</errorMessage>\n" +
             "</error>\n" +
             "</response>";
Document doc = DocumentBuilderFactory.newInstance()
                                     .newDocumentBuilder()
                                     .parse(new InputSource(new StringReader(xml)));

NodeList errNodes = doc.getElementsByTagName("error");
if (errNodes.getLength() > 0) {
    Element err = (Element)errNodes.item(0);
    System.out.println(err.getElementsByTagName("errorMessage")
                          .item(0)
                          .getTextContent());
} else { 
        // success
}
Belphegor
  • 4,456
  • 11
  • 34
  • 59
azz
  • 5,852
  • 3
  • 30
  • 58
2

I would probably use an XML parser to convert it into XML using DOM, then get the text. This has the advantage of being robust and coping with any unusual situations such as a line like this, where something has been commented out:

<!-- commented out <errorMessage>ERROR HERE!!!</errorMessage> -->

If you try and parse it yourself then you might fall foul of things like this. Also it has the advantage that if the requirements expand, then its really easy to change your code.

http://docs.oracle.com/cd/B28359_01/appdev.111/b28394/adx_j_parser.htm

Paul Richards
  • 1,181
  • 1
  • 10
  • 29
1

It's an XML document. Use an XML parser.

You could tease it apart using string operations. But you have to worry about entity decoding, character encodings, CDATA sections etc. An XML parser will do all of this for you.

Check out JDOM for a simpler XML parsing approach than using raw DOM/SAX implementations.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440