如何告诉Xalan转义HTML属性中的字符

时间:2012-02-13 08:53:28

标签: java xml-serialization xalan

以下Java代码的结果是

<input value="<http://example.org/>">

我想要的是

<input value="&lt;http://example.org/&gt;">

代码是

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逃脱&lt;和&gt;人物正确?它导致ajax调用的客户端出现问题。

1 个答案:

答案 0 :(得分:0)

Apache Commons有一个StringEscapeUtils.escapeXml()和一个.unescapeXml()方法,您可以使用这些方法在将xml片段设置为属性之前将其转义。

input.setAttribute("value", StringEscapeUtils.escapeXml("<http://example.org/>"));

希望有所帮助,尽情享受!

相关问题