下面Java代码的结果是
<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
Xalan 是否有任何设置可以正确转义 < 和 > 字符?它会导致 ajax 调用的客户端出现问题。
最佳答案
Apache Commons 有一个 StringEscapeUtils.escapeXml()和一个 .unescapeXml() 方法,您可以使用这些方法在将 xml 片段设置为属性之前对其进行转义。
input.setAttribute("value", StringEscapeUtils.escapeXml("<http://example.org/>"));
希望对您有所帮助,祝您愉快!
关于java - 如何告诉 Xalan 转义 HTML 属性中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9257718/