Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
155 views
in Technique[技术] by (71.8m points)

java - XMLStreamWriter writeCharacters without escaping

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(){ 
"+
      " alert('hello world');
" +
      "}
");
      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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...