title: Python: Unicode and ElementTree.parse
body: <p>I'm trying to move to Python 2.7 and since Unicode is a Big Deal there, I'd try dealing with them with XML files and texts and parse them using the <code>xml.etree.cElementTree</code> library. But I ran across this error:</p>
  
  <pre><code>&gt;&gt;&gt; import xml.etree.cElementTree as ET
  &gt;&gt;&gt; from io import StringIO
  &gt;&gt;&gt; source = """\
  ... &lt;?xml version="1.0" encoding="UTF-8" standalone="yes" ?&gt;
  ... &lt;root&gt;
  ...   &lt;Parent&gt;
  ...     &lt;Child&gt;
  ...       &lt;Element&gt;Text&lt;/Element&gt;
  ...     &lt;/Child&gt;
  ...   &lt;/Parent&gt;
  ... &lt;/root&gt;
  ... """
  &gt;&gt;&gt; srcbuf = StringIO(source.decode('utf-8'))
  &gt;&gt;&gt; doc = ET.parse(srcbuf)
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "&lt;string&gt;", line 56, in parse
    File "&lt;string&gt;", line 35, in parse
  cElementTree.ParseError: no element found: line 1, column 0
  </code></pre>
  
  <p>The same thing happens using <code>io.open('filename.xml', encoding='utf-8')</code> to pass to <code>ET.parse</code>:</p>
  
  <pre><code>&gt;&gt;&gt; with io.open('test.xml', mode='w', encoding='utf-8') as fp:
  ...     fp.write(source.decode('utf-8'))
  ...
  150L
  &gt;&gt;&gt; with io.open('test.xml', mode='r', encoding='utf-8') as fp:
  ...     fp.read()
  ...
  u'&lt;?xml version="1.0" encoding="UTF-8" standalone="yes" ?&gt;\n&lt;root&gt;\n  &lt;Parent&gt;\n
      &lt;Child&gt;\n      &lt;Element&gt;Text&lt;/Element&gt;\n    &lt;/Child&gt;\n  &lt;/Parent&gt;\n&lt;/root&gt;\n
  '
  &gt;&gt;&gt; with io.open('test.xml', mode='r', encoding='utf-8') as fp:
  ...     ET.parse(fp)
  ...
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 2, in &lt;module&gt;
    File "&lt;string&gt;", line 56, in parse
    File "&lt;string&gt;", line 35, in parse
  cElementTree.ParseError: no element found: line 1, column 0
  </code></pre>
  
  <p>Is there something about unicode and ET parsing that I am missing here?</p>
  
  <p><strong>edit</strong>: Apparently, the ET parser does not play well with unicode input stream? The following works:</p>
  
  <pre><code>&gt;&gt;&gt; with io.open('test.xml', mode='rb') as fp:
  ...     ET.parse(fp)
  ...
  &lt;ElementTree object at 0x0180BC10&gt;
  </code></pre>
  
  <p>But this also means I cannot use <code>io.StringIO</code> if I want to parse from an in-memory text, unless I encode it first into an in-memory buffer?</p>