How to tell Xalan to escape characters in HTML attributes

旧巷老猫 提交于 2019-12-12 19:22:51

问题


The result of the Java code below is

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

What I want is

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!