3

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.

  • I have a feeling setting the output method to "html" has something to do with it. I bet it won't happen if you set it to "xml" – Dagg Nabbit Feb 13 '12 at 08:56
  • This feeling is correct, but I can't set it to "xml" because the result is sent back to the client as HTML in an jQuery load request. So is this a bug in Xalan? –  Feb 13 '12 at 09:29
  • I think it would be a bug if you were telling it to produce XML. Since it's being told to produce HTML, what it's doing doesn't seem to be a bug. It's valid HTML, just not valid XML. A bit of googling suggests it also has an "xhtml" output method, have you tried that? – Dagg Nabbit Feb 13 '12 at 14:36
  • possible duplicate of [jQuery.load corrupts HTML tags from attributes](http://stackoverflow.com/questions/9256714/jquery-load-corrupts-html-tags-from-attributes) – Chamika Sandamal Feb 14 '12 at 04:33
  • @ChamikaSandamal I don't think it is. The post you linked is about working around a jQuery bug, this one is about getting Xalan to produce valid x(ht)ml. ISTM the post you linked requires an answer in the form "do X to get jquery to do Y" where this one requires an answer in the form "do X to get Xalan to do Y". – Dagg Nabbit Feb 15 '12 at 00:13

1 Answers1

0

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!

TA Nguyen
  • 453
  • 1
  • 3
  • 8