title: Nokogiri fails outputting XML with UTF-16 declaration (understanding and working around)
body: <h2>Summary</h2>
  
  <p>Attempting to read and serialize XML documents that have a UTF-16 encoding and declaration causes Nokogiri to produce garbage after a certain point. </p>
  
  <ol>
  <li>Is this a bug, or is there a reasonable explanation for this?</li>
  <li>What's the best way to avoid it?</li>
  </ol>
  
  <h2>Environment</h2>
  
  <pre class="lang-none prettyprint-override"><code>C:\&gt;nokogiri -v
  # Nokogiri (1.5.5)
      ---
      warnings: []
      nokogiri: 1.5.5
      ruby:
        version: 1.9.3
        platform: i386-mingw32
        description: ruby 1.9.3p194 (2012-04-20) [i386-mingw32]
        engine: ruby
      libxml:
        binding: extension
        compiled: 2.7.7
        loaded: 2.7.7
  </code></pre>
  
  <h2>Details</h2>
  
  <p>I have an XML file encoded with UTF-16(LE), and it also includes a PI XML Declaration at the top indicating that the encoding is UTF-16. Summarized, it looks like this:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-16" ?&gt;
  &lt;Foo&gt;
    &lt;Bar&gt;&lt;![CDATA[
  Lorem ipsum dolor ...about 3900 more bytes of content here...
    ]]&gt;&lt;/Bar&gt;
    &lt;Jim&gt;Oh! Hello there.&lt;/Jim&gt;
  &lt;/Foo&gt;
  </code></pre>
  
  <p>When I use Nokogiri to read this document, all seems well:</p>
  
  <pre class="lang-rb prettyprint-override"><code>xml = File.open('Simplified.xml','rb:utf-16le',&amp;:read)
  p xml.encoding                        # #&lt;Encoding:UTF-16LE&gt;
  p xml.valid_encoding?                 # true
  doc1 = Nokogiri.XML(xml,&amp;:noblanks)
  xml1 = doc1.to_xml.encode('utf-8')
  p xml1.encoding                       # #&lt;Encoding:UTF-8&gt;
  p xml1.valid_encoding?                # true
  </code></pre>
  
  <p>However, the output of serializing the document becomes munged after a certain point:</p>
  
  <pre class="lang-rb prettyprint-override"><code>p xml1  # Correct contents of CDATA removed from the following output
  #=&gt; "&lt;?xml version=\"1.0\" encoding=\"UTF-16\"?&gt;\n&lt;Foo&gt;\n  &lt;Bar&gt;&lt;![CDATA[\n...\n\t]]&gt;&lt;/Bar&gt;\n  &lt;Jim&gt;Oh! Hello there.\uFFFE\u3C00\u0000\u2F00\u0000\u4A00\u0000\u6900\u0000\u6D00\u0000\u3E00\u0000\u0A00\u0000\u3C00\u0000\u2F00\u0000\u4600\u0000\u6F00\u0000\u6F00\u0000\u3E00\u0000\u0A00\u0000"
  </code></pre>
  
  <p><sub>(The limit seems to be related to the number of characters. I can add and remove a few words from the Lorem ipsum text with no change, but removing text below a certain point suddenly fixes the output.)</sub></p>
  
  <p>The Nokogiri document is not broken, however. I can independently serialize <code>&lt;Jim&gt;</code> successfully:</p>
  
  <pre class="lang-rb prettyprint-override"><code>puts doc1.at('Jim').to_xml.encode('utf-8')
  #=&gt; &lt;Jim&gt;Oh! Hello there.&lt;/Jim&gt;
  </code></pre>
  
  <p>The only workaround I've found is to remove the XML Declaration at the top of the document before parsing it. With this, all works as desired:</p>
  
  <pre><code>decl = '&lt;?xml version="1.0" encoding="UTF-16" ?&gt;'.encode('UTF-16LE')
  doc2 = Nokogiri.XML(xml.sub(decl,''),&amp;:noblanks)
  puts doc2.to_xml.encode('utf-8')
  #=&gt; &lt;?xml version="1.0"?&gt;
  #=&gt; &lt;Foo&gt;
  #=&gt;   &lt;Bar&gt;&lt;![CDATA[
  #=&gt; Lorem ipsum dolor...and more...
  #=&gt;   ]]&gt;&lt;/Bar&gt;
  #=&gt;   &lt;Jim&gt;Oh! Hello there.&lt;/Jim&gt;
  #=&gt; &lt;/Foo&gt;
  </code></pre>
  
  <h2>Full XML</h2>
  
  <p>Here's the full file to test for yourself:</p>
  
  <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-16" ?&gt;
  &lt;Foo&gt;
    &lt;Bar&gt;&lt;![CDATA[
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac augue arcu, eget laoreet lorem. Quisque ac augue velit. Integer consectetur suscipit vehicula. Etiam et convallis enim. Etiam varius massa sit amet lacus rhoncus varius in non ante. Sed dictum, metus eu bibendum ornare, ligula dui commodo urna, ut dignissim felis dolor eget nisl. Proin sit amet nisi nunc. Vestibulum a urna sed dui dignissim blandit nec vel enim. Vivamus tincidunt nulla id dui hendrerit hendrerit.
  Aliquam neque orci, luctus sit amet fringilla eu, varius vitae diam. Suspendisse varius rutrum lorem eget malesuada. Sed dapibus dapibus nisl, in cursus ante lacinia non. Aenean id sagittis ipsum. Suspendisse elit nunc, porta sit amet blandit ut, laoreet sed est. Nunc eget sem vitae nisl elementum ullamcorper ut sit amet urna. Sed ligula quam, fringilla in facilisis tincidunt, vehicula in nisi. Maecenas a augue in augue semper scelerisque sit amet ut arcu.
  Praesent hendrerit, enim in elementum ornare, lorem nisi euismod dolor, sit amet ornare mi sem sodales lacus. Fusce et tempor mauris. In non quam nisl, non consequat diam. Duis sit amet massa ultrices massa cursus iaculis. Nunc ullamcorper malesuada sem dignissim semper. Fusce aliquet lacus quis nisi tincidunt sodales. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque posuere commodo aliquet. Aliquam blandit vestibulum facilisis. Sed pellentesque viverra dignissim. Etiam est lacus, mollis eu pretium vitae, lacinia eleifend augue. Mauris vitae quam nisl. In venenatis nunc ac eros elementum cursus.
  Sed a metus sit amet nunc euismod condimentum id non orci. Curabitur velit turpis, lacinia non eleifend sed, rhoncus id est. Fusce ut massa dolor, ut sodales odio. Donec aliquam convallis tellus, eu pharetra tortor iaculis non. Integer imperdiet feugiat ipsum a gravida. Mauris sapien ipsum, ultricies ac placerat ut, imperdiet eu justo. Quisque quis consectetur velit. Etiam facilisis sapien nec enim tincidunt pulvinar. Duis fermentum faucibus felis, sed consequat libero pretium at. Phasellus nibh purus, suscipit in vestibulum vel, blandit at leo. Suspendisse placerat elit sed enim bibendum vel hendrerit mauris pretium. Maecenas ut lacus eu nisi euismod pretium.
  Aliquam feugiat felis id massa aliquam pharetra sed non eros. Morbi interdum molestie iaculis. Curabitur varius ante ac dui dapibus non laoreet risus blandit. Nunc sit amet magna lacus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus egestas nunc sed turpis imperdiet a rhoncus massa aliquam. Nulla facilisi. Phasellus sit amet neque felis, nec vestibulum massa. Donec luctus fringilla dolor et gravida. Phasellus euismod lectus eget elit hendrerit non vehicula tellus venenatis. Phasellus sit amet ligula et purus dignissim feugiat at vitae libero. Proin ut tortor eros, quis laoreet lectus. Quisque nec urna mattis ante gravida fermentum eu at nibh. Phasellus sapien elit, tincidunt quis laoreet id, lobortis sed magna. Aliquam pulvinar erat eu sapien pretium bibendum. Maecenas eleifend, leo quis sodales tincidunt, leo felis tristique dolor, vitae ultrices neque felis ut metus.
  Etiam dignissim egestas ipsum, eget tempor ipsum rutrum eu. Donec vehicula eleifend ullamcorper. Mauris justo nulla, varius a mattis a, cursus sit amet risus. Phasellus rutrum interdum blandit. Donec ut justo eros, ut auctor dolor. Suspendisse potenti. Cras ultricies, dui eget mattis bibendum, leo dui luctus purus, sit amet rhoncus libero metus eget purus. Pellentesque scelerisque ornare sapien faucibus tempor.
  Suspendisse potenti. Proin fermentum bibendum dapibus. Pellentesque facilisis aliquam. Nam egestas tellus non mauris scelerisque feugiat pellentesque lacus dignissim. Quisque id nulla felis. Mauris justo mauris, posuere sed facilisis in, venenatis nec risus. Mauris eu dui sed tellus laoreet tempor a in turpis volutpat.
    ]]&gt;&lt;/Bar&gt;
    &lt;Jim&gt;Oh! Hello there.&lt;/Jim&gt;
  &lt;/Foo&gt;
  </code></pre>