Note that there are some explanatory texts on larger screens.

plurals
  1. POlxml adds urlencoding in xml?
    primarykey
    data
    text
    <p>I'll preface this by indicating I'm using Python 2.7.3 (x64) on Windows 7, with lxml 2.3.6.</p> <p>I have a little, odd, problem I'm hoping somebody can help with. I haven't find a solution online, perhaps I'm not searching for the right thing.</p> <p>Anyway, I have a problem where I'm programmatically building some XML with lxml, then outputting this to a text file, the problem is lxml is converting carriage returns to the text <code>&amp;#13;</code>, almost like urlencoding - but I'm not using HTML I'm using XML.</p> <p>For example, I have a simple text file created in Notepad, like this:</p> <pre><code>This is my text </code></pre> <p>I then build some xml and add this text into the xml:</p> <pre><code>from lxml import etree textstr = "" fh = open("mytext.txt", "rb") for line in fh: textstr += line root = etree.Element("root") a = etree.SubElement(root, "some_element") a.text = textstr print etree.tostring(root) </code></pre> <p>The problem here is the output of the print looks like this:</p> <pre><code>&lt;root&gt;&lt;some_element&gt;This&amp;#13; is&amp;#13; my&amp;#13; text&lt;/some_element&gt;&lt;/root&gt; </code></pre> <p>For my purposes the line breaks are fine, but the <code>&amp;#13;</code> elements are not.</p> <p>What I have been able to figure out is that this is happening because I'm opening the text file in binary mode <code>"rb"</code> (which I actually need to do as my app is indexing a large text file). If I don't open the file in binary mode <code>"r"</code>, then the output does not contain <code>&amp;#13;</code> (but of course, then my indexing doesn't work).</p> <p>I've also tried changing the <code>etree.tostring</code> to:</p> <pre><code>print etree.tostring(root, method="xml") </code></pre> <p>However there is no difference in the output.</p> <p>Now, I CAN dump the xml text to a string then do a replace of the <code>$#13;</code> artifacts, however, I was hoping for a more elegant solution - because the text files I parse are not under my control and I'm worried that other elements of the text file might be converted to url style encoding without my knowledge.</p> <p>Does anyone know a way of preventing this encoding from happening?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload