如何解析<![CDATA []]>的XML

GOK*_*GOK 8 java xml parsing cdata

如何解析包含数据的XML <![CDATA[---]...如何解析xml并获取包含在CDATA???中的数据?

小智 8

public static void main(String[] args) throws Exception {
  File file = new File("data.xml");
  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
 //if you are using this code for blackberry xml parsing
  builder.setCoalescing(true);
  Document doc = builder.parse(file);

  NodeList nodes = doc.getElementsByTagName("topic");
  for (int i = 0; i < nodes.getLength(); i++) {
    Element element = (Element) nodes.item(i);
    NodeList title = element.getElementsByTagName("title");
    Element line = (Element) title.item(0);
    System.out.println("Title: " + getCharacterDataFromElement(line));
  }
}
public static String getCharacterDataFromElement(Element e) {
  Node child = e.getFirstChild();
  if (child instanceof CharacterData) {
    CharacterData cd = (CharacterData) child;
    return cd.getData();
  }
  return "";
}
Run Code Online (Sandbox Code Playgroud)

(http://www.java2s.com/Code/Java/XML/GetcharacterdataCDATAfromxmldocument.htm)