本示例演示如何将CDATA部分添加到xml文档中。一个CDATA部分指示不应解析的块。要构建一个CDATA节,只需将字符串与CDATA对象包装在一起。
package org.nhooo.example.jdom; import org.jdom2.CDATA; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import java.io.IOException; import java.io.StringReader; public class JDOMBuildCDATASection { public static void main(String[] args) { String xml = "<root>" + " <comments>" + " <comment></comment>" + " </comments>" + "</root>"; SAXBuilder builder = new SAXBuilder(); try { Document document = builder.build(new StringReader(xml)); Element root = document.getRootElement(); Element comments = root.getChild("comments"); Element comment = comments.getChild("comment"); // 使用setContent和addContent添加CDATA部分 // 到xml元素中。 comment.setContent( new CDATA("<b>This is a bold string</b>.")); comment.addContent( new CDATA("<i>And this an italic string</i>.")); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(document, System.out); // 只需调用以下命令即可读取CDATA部分 //getText方法。不管它是否是一个简单的字符串 // 或CDATA部分,它只会将内容返回为 // 串。 String text = comment.getText(); System.out.println("Text = " + text); } catch (JDOMException | IOException e) { e.printStackTrace(); } } }
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/jdom/jdom2/2.0.6/jdom2-2.0.6.jar --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>