title: Java: XML escape the special characters
body: <p>I understand that XML has 5 special characters that MUST be escaped (",',&lt;,>,&amp;)
  I am trying to implement the following: </p>
  
  <p>Input xml:</p>
  
  <pre><code>&lt;?xml version = "1.0"?&gt;
  &lt;class&gt;
    &lt;student id = "999"&gt;
    &lt;firstname&gt;Tes"Ting&lt;/firstname&gt;
    &lt;lastname&gt;He'llo&lt;/lastname&gt;
    &lt;nickname1&gt;W&lt;or&gt;ld&lt;/nickname&gt;
    &lt;nickname2&gt;star&amp;wars&lt;/nickname2&gt;
    &lt;/student&gt;
  &lt;/class&gt;
  </code></pre>
  
  <p>Output XML:</p>
  
  <pre><code> &lt;?xml version = "1.0"?&gt;
    &lt;class&gt;
    &lt;student id = "999"&gt;
    &lt;firstname&gt;Tes&amp;quot;Ting&lt;/firstname&gt;
    &lt;lastname&gt;He&amp;apos;llo&lt;/lastname&gt;
    &lt;nickname&gt;W&amp;lt;orl&amp;gt;d&lt;/nickname&gt;
    &lt;nickname2&gt;star&amp;amp;wars&lt;/nickname2&gt;
    &lt;/student&gt;
  &lt;/class&gt;
  </code></pre>
  
  <p>Following is my code which works fine if there is single quote (') and double quotes ("). 
  When the code finds &amp;, &lt;, >..the XML parser throws an error. Can anyone please suggest how to implement? any thoughts?</p>
  
  <pre><code>import org.xml.sax.SAXException;
  import org.w3c.dom.*;
  import javax.xml.parsers.*;
  import java.io.IOException;
  import com.vordel.trace.Trace;
  import org.xml.sax.InputSource;
  import org.apache.commons.lang.StringEscapeUtils;
  
  ========Logic=====
      def input = &lt;input xml in string&gt;   
      def temp;
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();   
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(new InputSource(new StringReader(input)));
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("student");
  
      for (temp = 0; temp &lt; nList.getLength(); temp++) 
      {
        Node nNode = nList.item(temp);          
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
           Element eElement = (Element) nNode;
           escapedfirstname=     StringEscapeUtils.escapeXml(eElement.getElementsByTagName("firstname").item(0).getTextContent() );
  
           escapedlastname= StringEscapeUtils.escapeXml(eElement.getElementsByTagName("lastname").item(0).getTextContent() );
  
             }
           }
  </code></pre>