问题
The result of the Java code below is
<input value="<http://example.org/>">
What I want is
<input value="<http://example.org/>">
The code is
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element input = doc.createElement("input");
input.setAttribute("value", "<http://example.org/>");
Transformer xform = TransformerFactory.newInstance().newTransformer();
xform.setOutputProperty(OutputKeys.INDENT, "yes");
xform.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
xform.setOutputProperty(OutputKeys.ENCODING, "utf-8");
xform.setOutputProperty(OutputKeys.METHOD, "html");
StringWriter writer = new StringWriter();
xform.transform(new DOMSource(input), new StreamResult(writer));
System.out.println(writer.toString());
The implementation of xform is com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
Is there any setting for Xalan that will escape the < and > characters correctly? It is causing problems in client side of ajax calls.
回答1:
Apache Commons have a StringEscapeUtils.escapeXml() and a .unescapeXml() methods that you can use to escape the xml fragment before setting it to the attribute.
input.setAttribute("value", StringEscapeUtils.escapeXml("<http://example.org/>"));
Hope that help, enjoy!
来源:https://stackoverflow.com/questions/9257718/how-to-tell-xalan-to-escape-characters-in-html-attributes