问题描述
下面Java代码的结果是
The result of the Java code below is
<input value="<http://example.org/>">
我想要的是
<input value="<http://example.org/>">
代码是
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());
xform 的实现是 com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
The implementation of xform is com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
Xalan 是否有任何设置可以逃避 <和 > 字符正确吗?它导致 ajax 调用的客户端出现问题.
Is there any setting for Xalan that will escape the < and > characters correctly? It is causing problems in client side of ajax calls.
推荐答案
Apache Commons 有一个 StringEscapeUtils.escapeXml() 和可用于转义 xml 的 .unescapeXml() 方法将其设置为属性之前的片段.
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!
这篇关于如何告诉 Xalan 转义 HTML 属性中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!