从CDATA中提取元素

时间:2013-05-17 12:21:59

标签: java xml cdata

我有这个XML文件:

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

我需要提取tag1brb。这是我的代码:

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 "";
}

输出是:

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

但我需要String [] str以下值:

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

1 个答案:

答案 0 :(得分:2)

CDATA块的目的是将内容保存为未解析的字符数据(这是您所看到的)。获得String后,您可以对其进行解析以访问其数据。