1

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:";
1
  • Perhaps JAXB would be of interes to you. It lets you bind xml to standard Java classes. That way you wouldn't have to do any xml parsing of your own and it would be a lot quicker to adapt to changes in the xml schema. Commented May 17, 2013 at 12:27

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So are you suggesting I should use regex to split the string?
@Sam - Since <tag1 hello world/> isn't valid XML you will need to use something like regex to extract information from the String.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.