Java HTML / XML How to - Output XML escape code








Question

We would like to know how to output XML escape code.

Answer

import java.io.StringReader;
import java.io.StringWriter;
/* www  .  ja v  a2 s  .c  o  m*/
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

public class Main {

  public static void main(String[] args) throws Exception {
    XMLOutputFactory xof = XMLOutputFactory.newFactory();

    StringWriter sw = new StringWriter();
    XMLStreamWriter xsw = xof.createXMLStreamWriter(sw);
    xsw.writeStartDocument();
    xsw.writeStartElement("foo");
    xsw.writeCharacters("<>\"&'");
    xsw.writeEndDocument();

    String xml = sw.toString();
    System.out.println(xml);

    // READ THE XML
    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
    xsr.nextTag(); // Advance to "foo" element
    System.out.println(xsr.getElementText());
  }

}