Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XMLStreamWriter writeCharacters without escaping

Tags:

java

xml

How do I use XMLStreamWriter to write exactly what I put in? For instance, if I create script tag and fill it with javascript I don't want all my single quotes coming out as '

Here's a small test I wrote that doesn't use any of the abstractions I've got in place, just calls to writeCharacters.

  public void testWriteCharacters() {
    StringWriter sw = new StringWriter();
    XMLOutputFactory factory = XMLOutputFactory.newInstance();

    StringBuffer out = new StringBuffer();
    try {
      XMLStreamWriter writer = factory.createXMLStreamWriter(sw);
      writer.writeStartElement("script");
      writer.writeAttribute("type","text/javascript");
      writer.writeCharacters("function hw(){ \n"+
      "\t alert('hello world');\n" +
      "}\n");
      writer.writeEndElement();
      out.append(sw);
    } catch (XMLStreamException e) {
    } finally {
      try {
        sw.close();
      } catch(IOException e) {
        e.printStackTrace();
      }
    }
    System.out.println(out.toString());
  }

This produces an apos entity for both the single quotes surrounding hello world.

like image 391
Felix Avatar asked May 06 '10 19:05

Felix


2 Answers

You could use a property on the factory:

final XMLOutputFactory streamWriterFactory = XMLOutputFactory.newFactory();
streamWriterFactory.setProperty("escapeCharacters", false);

Then the writer created by this factory will write characters without escaping the text in the element given that the factory supports this property. XMLOutputFactoryImpl does.

like image 125
Bodum R Mugg Avatar answered Oct 13 '22 21:10

Bodum R Mugg


XmlStreamWriter.writeCharacters() doesn't escape '. It only escapes <, > and &, and writeAttribute also escapes " (see javadoc).

However, if you want to write text without escaping at all, you have to write it as a CDATA section using writeCData().

The typical approach for writing scripts in CDATA sections is:

<script>//<![CDATA[
    ...
//]]></script>

That is:

out.writeCharacters("//");
out.writeCData("\n ... \n//");
like image 26
axtavt Avatar answered Oct 13 '22 21:10

axtavt