title: Removing invalid characters from XML before serializing it with XMLSerializer()
body: <p>I'm trying to store user-input in an XML document on the client-side (javascript), and transmit that to the server for persistence. </p>
  
  <p>One user, for example, pasted in text that included an STX character (0x2). The XMLSerializer did not escape the STX character, and therefore, did not serialize to well-formed XML. Or perhaps the .attr() call should have escaped the STX character, but in either case, invalid XML was produced.</p>
  
  <p>I'm finding the output of in-browser XMLSerializer() isn't always well-formed, (and doesn't even satisfy the browser's own DOMParser()</p>
  
  <p>This example shows that the STX character is not properly encoded by XMLSerializer():</p>
  
  <pre><code>&gt; doc = $.parseXML('&lt;?xml version="1.0" encoding="utf-8" ?&gt;\n&lt;elem&gt;&lt;/elem&gt;');
      #document
  &gt; $(doc).find("elem").attr("someattr", String.fromCharCode(0x2));
      [ &lt;elem someattr=​""&gt;​&lt;/elem&gt;​ ]
  &gt; serializedDoc = new XMLSerializer().serializeToString(doc);
      "&lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;elem someattr=""/&gt;&lt;/elem&gt;"
  &gt; $.parseXML(serializedDoc);
      Error: Invalid XML: &lt;?xml version="1.0" encoding="utf-8"?&gt;&lt;elem someattr=""/&gt;&lt;/elem&gt;
  </code></pre>
  
  <p>How should I construct an XML document in-browser (with params determined by arbitrary user-input) such that it will always be well-formed (everything properly escaped)? I don't need to support IE8 or IE7.</p>
  
  <p>(And yes, I do validate the XML on the server side, but if the browser hands the server a document that is not well-formed, the best the server can do is reject it, which isn't that helpful to the poor user)</p>