Java examples for XML:XML Attribute
This will take the pre-defined entities in XML 1.0 and convert their character representation to the appropriate entity reference, suitable for XML attributes.
import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Node; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.*; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import java.io.*; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class Main{ /**/*from w ww. j a va 2s .c o m*/ * This will take the pre-defined entities in XML 1.0 and convert their * character representation to the appropriate entity reference, suitable * for XML attributes. * * @param text * text * * @return text with entities escaped */ public static String escapeElementEntities(String text) { StringBuffer buffer = new StringBuffer(); char[] block = null; int i; int last = 0; int size = text.length(); for (i = 0; i < size; i++) { String entity = null; char c = text.charAt(i); switch (c) { case '<': entity = "<"; break; case '>': entity = ">"; break; case '&': entity = "&"; break; case '\t': case '\n': case '\r': // // don't encode standard whitespace characters // if (preserve) { // entity = String.valueOf(c); // } break; default: if ((c < 32)) { entity = "&#" + (int) c + ";"; } // if ((c < 32) || shouldEncodeChar(c)) { // entity = "&#" + (int) c + ";"; // } break; } if (entity != null) { if (block == null) { block = text.toCharArray(); } buffer.append(block, last, i - last); buffer.append(entity); last = i + 1; } } if (last == 0) { return text; } if (last < size) { if (block == null) { block = text.toCharArray(); } buffer.append(block, last, i - last); } String answer = buffer.toString(); buffer.setLength(0); return answer; } }