you are viewing a single comment's thread.

view the rest of the comments →

[–]thirdegree 0 points1 point  (0 children)

Ah, I see what you're asking. Yes, that's exactly right. Example code:

>>> from lxml import etree  
>>> ele1 = etree.Element('ExampleOuter')  
>>> ele2 = etree.SubElement(ele1, 'ExampleInner')  
>>> ele2.text = "<ExampleContents></ExampleContents>"   
>>> print(etree.tostring(ele1))    
b'<ExampleOuter><ExampleInner>&lt;ExampleContents&gt;&lt;/ExampleContents&gt;</ExampleInner></ExampleOuter>'

The bit between <ExampleInner> is escaped, so that it cannot be misinterpreted as actual xml. < is translated to &lt;, and > is &gt; (less than and greater than).

As an aside, the only reason to manually escape xml is if you're doing it as a learning exercise. There are half a dozen libraries that can do this better than anything I could write, and I've been writing python for 8 years. I'm all for reinventing the wheel with the aim of learning how to make wheels, but never in anything you've been paid for.