Java examples for XML:XML String
Quote a string, and write to a PrintWriter for XML.
/*//from www. jav a 2 s . c o m // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde licenses this file to you under the Apache License, // Version 2.0 (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ import java.io.IOException; import java.io.PrintWriter; import java.io.Reader; public class Main{ /** * Quote a string, and write to a {@link PrintWriter}. * * <p>For example, <code>"a string"</code> becomes <code><![CDATA[a * string]]></code>. If the string contains ']]>' (which commonly * occurs when wrapping other XML documents), we give up on using * <code><![CDATA[</code> ... <code>]]></code>, and just encode the * string. For example, <code>"A string with ]]> in it"</code> becomes * <code>"A string with ]]&gt; in it"</code>.</p> */ public static void printPCDATA(PrintWriter pw, String data) { if (data.indexOf("]]>") > -1) { String s = StringEscaper.xmlEscaper.escapeString(data); pw.print(s); } else { pw.print("<![CDATA["); pw.print(data); pw.print("]]>"); } } /** * Quote a string in an element and a CDATA, and write to a {@link * PrintWriter}. For example, it <code>tag</code> is "Value", then * <code>"a string"</code> becomes <code><Value><![CDATA[a * string]]></Value></code>. * * @param newline whether to print a newline after the element * @see #printPCDATA(PrintWriter,String) */ public static void printPCDATA(PrintWriter pw, String tag, String data, boolean newline) { if (data == null || data.length() == 0) { return; } pw.print("<"); pw.print(tag); pw.print(">"); printPCDATA(pw, data); pw.print("</"); pw.print(tag); pw.print(">"); if (newline) { pw.println(); } } public static void printPCDATA(PrintWriter pw, String tag, String data) { boolean newline = false; printPCDATA(pw, tag, data, newline); } }