hamid
hamid

Reputation: 2079

Extracting elements from CDATA

I have this XML file:

<description>
  <![CDATA[
    <tag1 hello world/><br/> 
    <b>Current Conditions:</b>
  ]]>
</description>

I need to extracttag1, br and b. Here is my code:

NodeList nl = eElement.getElementsByTagName("description");

for (int j = 0; j < nl.getLength(); j++) {
    Node n = nl.item(j);
    Element e = (Element)n;
    String s = getElement(e));
}


public static String getElement(Element e) {
    NodeList list = e.getChildNodes();
    String data;

    for(int index = 0; index < list.getLength(); index++){
        if(list.item(index) instanceof CharacterData){
            CharacterData child = (CharacterData) list.item(index);
            data = child.getData();

            if(data != null && data.trim().length() > 0)
                return child.getData();
        }
    }
    return "";
}

Output is:

<tag1 hello world/><br/> 
<b>Current Conditions:</b> 

But I need to have a String [] str with following values:

 str[0] = "hello world";
 str[1] = ""; 
 str[3] = "Current Condition:";

Upvotes: 1

Views: 1254

Answers (1)

bdoughan
bdoughan

Reputation: 149047

The purpose of the CDATA block is to preserve the content as un-parsed character data (which is what you are seeing). Once you have the String you could parse that to access it's data.

Upvotes: 2

Related Questions