0

I have below string CDATA format from the response of a webservice call.

String outputString = "<![CDATA[<MYTAG><MYTAG1 type=\"java.util.vector\"><MyTAG2    type=\"java.util.hashtable\"><NAME type=\"java.lang.string\">XYZ</NAME><ADDRESS type=\"java.lang.string\">ABCD</ADDRESS></MYTAG2></MYTAG1></MYTAG>]]>"

When i tried with DOM parser. This string is giving exception.

DocumentBuilder builder;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
builder = factory.newDocumentBuilder();
Document outputXMLDocument = builder.parse(new InputSource(new StringReader(outputString)));
NodeList nodes = outputXMLDocument.getElementsByTagName("MYTAG");

I want to parse this respone and retrieve the value of NAME and ADDRESS TAG. Please advice for best way to handle this.

Lalit Gupta
  • 11
  • 1
  • 2
  • Please check this SO question - http://stackoverflow.com/questions/8489151/how-to-parse-xml-for-cdata It might help. – Keerthivasan Sep 18 '14 at 05:43
  • That CDATA value must have come out of an XML file as the text valud of an enclosing node. When you were parsing the containing XML you would have a text node. Fire up another `DocumentBuilder` and feed it the string value extracted from the text node. At that point it won't be a CDATA section since CDATA is present only in the serialized version of the document, never in the DOM. – Jim Garrison Sep 18 '14 at 05:45
  • In response of webservice call.. I don't have any node preceeding to CDATA. Ratiher it just have string as i mentioned String outputString = "<![CDATA[XYZ
    ABCD
    ]]>"
    – Lalit Gupta Sep 18 '14 at 05:58

1 Answers1

0

The data inside CDATA will not be parsed by the parser. The section inside CDATA is intended to have data that can't be sent in a XML. Say if you have < and & in XML, they have their own special meaning. These type of content are placed in CDATA section

The below snippet can help you parse the character data from the element.

public static String getCharacterDataFromElement(Element e) {
  Node child = e.getFirstChild();
  if (child instanceof CharacterData) {
    CharacterData cd = (CharacterData) child;
      System.out.println(cd.getData());
    return cd.getData();
  }
  return "";
}

You can create a document with the response you get from webservice and then perform the parsing, if just CDATA is available.

Hope it helps!

Keerthivasan
  • 12,760
  • 2
  • 32
  • 53