用xom包编写<![CDATA[]]>段备忘
xom-1.1.jar包是一个操作xml文件的jar包,利用该jar包可以很方便的操作xml文件。但是,该.jar包中并没有现成的生成xml的<!]>段的函数。在经过查了许多网上资料后,该官方网站好像是说<!]>段不安全,经常被人误用,所以不提供生成<!]>段的函数。但与此同时,在官网上一个国外网友,利用xom包现有的函数,写了一个生成<!]>段的类,来对官网的解释表示抗议。特此记录如下,代码比较简单,就不解释了。 :)
import java.io.IOException; import java.io.StringReader;
import nu.xom.Builder; import nu.xom.Document; import nu.xom.ParsingException; import nu.xom.Text;
/**
-
创建CDATA段的辅助类 */ public class CDATAFactory { private static final Text PROTOTYPE; // this is really an instance of CDATASection
static { Text temp = null;
try { // XOM preserves existing CDATA's so start with a doc that has one String docWithCDATA = "<text><!]></text>"; Builder builder = new Builder(); Document document = builder.build(new StringReader(docWithCDATA)); // grab the resulting CDATASection and keep it around as a prototype temp = (Text) document.getRootElement().getChild(0); temp.detach(); } catch (IOException e) { // not worried about IOExceptions just reading a string } catch (ParsingException e) { // already know this document is valid and will parse } PROTOTYPE = temp;}
public static Text makeCDATASection(String value) { // use copy and setValue to get a brand new CDATA section Text result = (Text) PROTOTYPE.copy(); result.setValue(value); return result; } }