title: Escaping special character when generating an XML in Java
body: <p>I am trying to develop an XML export feature to give my application users to export their data in an XML format. I have got this feature ready and working until it started failing for some cases. Then I realized that it was because of some special characters that needs to be encoded. for example the data might contain &amp; or ! or % or ' or # etc. etc. and this needs to be escaped properly.
  I was wondering if there is a generic utility available that can escape all of the special characters as per the XML specification. I couldn't find anything on Google.</p>
  
  <p>Is there something like that already there? or Is there any other way to do it?</p>
  
  <p>Here is the code I am using to generate XML <br/></p>
  
  <pre><code>
  Document xmldoc = new DocumentImpl();
  Element root = xmldoc.createElement("Report");
  
  Element name= xmldoc.createElement((exportData.getChartName() == null) ? "Report" : exportData.getChartName());
  if (exportData.getExportDataList().size() > 0
      && exportData.getExportDataList().get(0) instanceof Vector) {
      // First row is the HEADER, i.e name
      Vector name = exportData.getExportDataList().get(0);
      for (int i = 1; i  value = exportData.getExportDataList().get(i);
          Element sub_root = xmldoc.createElement("Data");
          //I had to remove a for loop from here. StackOverflow description field would not take that. :(
              // Insert header row
              Element node = xmldoc.createElementNS(null, replaceUnrecognizedChars(name.get(j)));
              Node node_value = xmldoc.createTextNode(value.get(j));
              node.appendChild(node_value);
              sub_root.appendChild(node);
              chartName.appendChild(sub_root);
          }
      }
  }
  root.appendChild(name);
  
  // Prepare the DOM document for writing
  Source source = new DOMSource(root);
  
  // Prepare the output file
  Result result = new StreamResult(file);
  
  // Write the DOM document to the file
  Transformer xformer = TransformerFactory.newInstance().newTransformer();
  xformer.transform(source, result);`
  </code></pre>
  
  <p>Sample XML:</p>
  
  <pre><code>
  &lt;Data&gt;
      &lt;TimeStamp&gt;2010-08-31 00:00:00.0&lt;/TimeStamp&gt;
      &lt;[Name that needs to be encoded]&gt;0.0&lt;/[Name that needs to be encoded]&gt;
      &lt;Group_Average&gt;1860.0&lt;/Group_Average&gt;
  &lt;/Data&gt;
  </code></pre>