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

标签 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 是否有任何设置可以正确转义 < 和 > 字符?它会导致 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/

相关文章:

java - 解码到内部静态类字段

Java接口(interface)命名协议(protocol)

java - URIResolver、Docbook 和 XSL 转换

java - XSL 转换无法调用用户定义的 Java 方法

java - 将字符串转换为等效的枚举值

c# - 从 XML 转换数组

c# - 在 C# 中更改由 XmlSerializer 生成的 XML 结构

c# - 提高 DataTable.ReadXml 性能

java - ant - 尝试复制到/lib/endorsed,库在 Windows 7 中无法用于下一个任务

java - @Formula注释不理解 "count"