<p>I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it.  </p>

<p>Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python.  </p>

<p>Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple.</p>

[{'answer_id': 342, 'author': 'saint_groceon', 'author_id': 59, 'author_profile': 'https://Stackoverflow.com/users/59', 'pm_score': 6, 'selected': True, 'text': '<p>Personally, I\'ve played with several of the built-in options on an XML-heavy project and have settled on <a href="http://docs.python.org/lib/module-xml.dom.pulldom.html" rel="noreferrer">pulldom</a> as the best choice for less complex documents.</p>\n\n<p>Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure.  <a href="http://www.prescod.net/python/pulldom.html" rel="noreferrer">Here is a good quick discussion of how to use the API</a>.</p>\n\n<p>What I like: you can handle the parsing in a <code>for</code> loop rather than using callbacks.  You also delay full parsing (the "pull" part) and only get additional detail when you call <code>expandNode()</code>.  This satisfies my general requirement for "responsible" efficiency without sacrificing ease of use and simplicity.</p>\n'}, {'answer_id': 471, 'author': 'Gareth Simpson', 'author_id': 147, 'author_profile': 'https://Stackoverflow.com/users/147', 'pm_score': 5, 'selected': False, 'text': '<p><a href="http://effbot.org/zone/element-index.htm" rel="noreferrer">ElementTree</a> has a nice pythony API.  I think it\'s even shipped as part of python 2.5</p>\n\n<p>It\'s in pure python and as I say, pretty nice, but if you wind up needing more performance, then <a href="http://codespeak.net/lxml/" rel="noreferrer">lxml</a> exposes the same API and uses libxml2 under the hood.  You can theoretically just swap it in when you discover you need it.</p>\n'}, {'answer_id': 525, 'author': 'Matt', 'author_id': 154, 'author_profile': 'https://Stackoverflow.com/users/154', 'pm_score': 3, 'selected': False, 'text': '<p>Since you mentioned that you\'ll be building "fairly simple" XML, the <a href="http://www.python.org/doc/current/lib/module-xml.dom.minidom.html" rel="noreferrer">minidom module</a> (part of the Python Standard Library) will likely suit your needs. If you have any experience with the DOM representation of XML, you should find the API quite straight forward.</p>\n'}, {'answer_id': 635, 'author': 'Matthew Schinckel', 'author_id': 188, 'author_profile': 'https://Stackoverflow.com/users/188', 'pm_score': 3, 'selected': False, 'text': '<p>I write a SOAP server that receives XML requests and creates XML responses.  (Unfortunately, it\'s not my project, so it\'s closed source, but that\'s another problem).</p>\n\n<p>It turned out for me that creating (SOAP) XML documents is fairly simple if you have a data structure that "fits" the schema.</p>\n\n<p>I keep the envelope since the response envelope is (almost) the same as the request envelope.  Then, since my data structure is a (possibly nested) dictionary, I create a string that turns this dictionary into &lt;key>value&lt;/key> items.  </p>\n\n<p>This is a task that recursion makes simple, and I end up with the right structure.  This is all done in python code and is currently fast enough for production use.</p>\n\n<p>You can also (relatively) easily build lists as well, although depending upon your client, you may hit problems unless you give length hints.</p>\n\n<p>For me, this was much simpler, since a dictionary is a much easier way of working than some custom class.  For the books, generating XML is much easier than parsing!</p>\n'}, {'answer_id': 69410, 'author': 'Kent Quirk', 'author_id': 11072, 'author_profile': 'https://Stackoverflow.com/users/11072', 'pm_score': 3, 'selected': False, 'text': '<p>There are 3 major ways of dealing with XML, in general: dom, sax, and xpath. The dom model is good if you can afford to load your entire xml file into memory at once, and you don\'t mind dealing with data structures, and you are looking at much/most of the model. The sax model is great if you only care about a few tags, and/or you are dealing with big files and can process them sequentially. The xpath model is a little bit of each -- you can pick and choose paths to the data elements you need, but it requires more libraries to use.</p>\n\n<p>If you want straightforward and packaged with Python, minidom is your answer, but it\'s pretty lame, and the documentation is "here\'s docs on dom, go figure it out". It\'s really annoying.</p>\n\n<p>Personally, I like cElementTree, which is a faster (c-based) implementation of ElementTree, which is a dom-like model.</p>\n\n<p>I\'ve used sax systems, and in many ways they\'re more "pythonic" in their feel, but I usually end up creating state-based systems to handle them, and that way lies madness (and bugs).</p>\n\n<p>I say go with minidom if you like research, or ElementTree if you want good code that works well.</p>\n'}, {'answer_id': 69772, 'author': 'mbesso', 'author_id': 9510, 'author_profile': 'https://Stackoverflow.com/users/9510', 'pm_score': 2, 'selected': False, 'text': '<p>I assume that the .NET way of processing XML builds on some version of MSXML and in that case I assume that using, for example, minidom would make you feel somewhat at home. However, if it is simple processing you are doing, any library will probably do.</p>\n<p>I also prefer working with ElementTree when dealing with XML in Python because it is a very neat library.</p>\n'}, {'answer_id': 123307, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 3, 'selected': False, 'text': "<p>I've used ElementTree for several projects and recommend it. </p>\n\n<p>It's pythonic, comes 'in the box' with Python 2.5, including the c version cElementTree (xml.etree.cElementTree) which is 20 times faster than the pure Python version, and is very easy to use.</p>\n\n<p>lxml has some perfomance advantages, but they are uneven and you should check the benchmarks first for your use case.</p>\n\n<p>As I understand it, ElementTree code can easily be ported to lxml. </p>\n"}, {'answer_id': 199213, 'author': 'William McVey', 'author_id': 27642, 'author_profile': 'https://Stackoverflow.com/users/27642', 'pm_score': 2, 'selected': False, 'text': '<p>If you\'re going to be building SOAP messages, check out <a href="http://trac.optio.webfactional.com/" rel="nofollow noreferrer">soaplib</a>. It uses ElementTree under the hood, but it provides a much cleaner interface for serializing and deserializing messages.</p>\n'}, {'answer_id': 202259, 'author': 'giltay', 'author_id': 21106, 'author_profile': 'https://Stackoverflow.com/users/21106', 'pm_score': 3, 'selected': False, 'text': '<p>It depends a bit on how complicated the document needs to be.</p>\n\n<p>I\'ve used minidom a lot for writing XML, but that\'s usually been just reading documents, making some simple transformations, and writing them back out. That worked well enough until I needed the ability to order element attributes (to satisfy an ancient application that doesn\'t parse XML properly). At that point I gave up and wrote the XML myself.</p>\n\n<p>If you\'re only working on simple documents, then doing it yourself can be quicker and simpler than learning a framework. If you can conceivably write the XML by hand, then you can probably code it by hand as well (just remember to properly escape special characters, and use <code>str.encode(codec, errors="xmlcharrefreplace")</code>). Apart from these snafus, XML is regular enough that you don\'t <em>need</em> a special library to write it. If the document is too complicated to write by hand, then you should probably look into one of the frameworks already mentioned. At no point should you need to write a general XML writer.</p>\n'}, {'answer_id': 7954780, 'author': 'Jabba', 'author_id': 232485, 'author_profile': 'https://Stackoverflow.com/users/232485', 'pm_score': 3, 'selected': False, 'text': '<p>You can also try <a href="https://github.com/stchris/untangle" rel="noreferrer">untangle</a> to parse simple XML documents.</p>\n'}, {'answer_id': 13832269, 'author': 'Arcturus', 'author_id': 1527852, 'author_profile': 'https://Stackoverflow.com/users/1527852', 'pm_score': 2, 'selected': False, 'text': '<p>I strongly recommend <code>SAX - Simple API for XML</code> - implementation in the Python libraries. They are fairly easy to setup and process large <code>XML</code> by even driven <code>API</code>, as discussed by previous posters here, and have low memory footprint unlike validating <code>DOM</code> style <code>XML</code> parsers.</p>\n'}, {'answer_id': 23143835, 'author': 'Jan Vlcinsky', 'author_id': 346478, 'author_profile': 'https://Stackoverflow.com/users/346478', 'pm_score': 3, 'selected': False, 'text': '<h1>For serious work with XML in Python use lxml</h1>\n\n<p>Python comes with ElementTree built-in library, but lxml extends it in terms of speed and functionality (schema validation, sax parsing, XPath, various sorts of iterators and many other features).</p>\n\n<p>You have to install it, but in many places, it is already assumed to be part of standard equipment (e.g. Google AppEngine does not allow C-based Python packages, but makes an exception for lxml, pyyaml, and few others).</p>\n\n<h1>Building XML documents with E-factory (from lxml)</h1>\n\n<p>Your question is about building XML document.</p>\n\n<p>With lxml there are many methods and it took me a while to find the one, which seems to be easy to use and also easy to read.</p>\n\n<p>Sample code from <a href="http://lxml.de/tutorial.html#the-e-factory" rel="nofollow noreferrer">lxml doc on using E-factory</a> (slightly simplified):</p>\n\n<hr>\n\n<p>The E-factory provides a simple and compact syntax for generating XML and HTML:</p>\n\n<pre><code>&gt;&gt;&gt; from lxml.builder import E\n\n&gt;&gt;&gt; html = page = (\n...   E.html(       # create an Element called "html"\n...     E.head(\n...       E.title("This is a sample document")\n...     ),\n...     E.body(\n...       E.h1("Hello!"),\n...       E.p("This is a paragraph with ", E.b("bold"), " text in it!"),\n...       E.p("This is another paragraph, with a", "\\n      ",\n...         E.a("link", href="http://www.python.org"), "."),\n...       E.p("Here are some reserved characters: &lt;spam&amp;egg&gt;."),\n...     )\n...   )\n... )\n\n&gt;&gt;&gt; print(etree.tostring(page, pretty_print=True))\n&lt;html&gt;\n  &lt;head&gt;\n    &lt;title&gt;This is a sample document&lt;/title&gt;\n  &lt;/head&gt;\n  &lt;body&gt;\n    &lt;h1&gt;Hello!&lt;/h1&gt;\n    &lt;p&gt;This is a paragraph with &lt;b&gt;bold&lt;/b&gt; text in it!&lt;/p&gt;\n    &lt;p&gt;This is another paragraph, with a\n      &lt;a href="http://www.python.org"&gt;link&lt;/a&gt;.&lt;/p&gt;\n    &lt;p&gt;Here are some reserved characters: &amp;lt;spam&amp;amp;egg&amp;gt;.&lt;/p&gt;\n  &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<hr>\n\n<p>I appreciate on E-factory it following things</p>\n\n<h3>Code reads almost as the resulting XML document</h3>\n\n<p>Readability counts. </p>\n\n<h3>Allows creation of any XML content</h3>\n\n<p>Supports stuff like:</p>\n\n<ul>\n<li>use of namespaces</li>\n<li>starting and ending text nodes within one element</li>\n<li>functions formatting attribute content (see func CLASS in <a href="http://lxml.de/tutorial.html#the-e-factory" rel="nofollow noreferrer">full lxml sample</a>)</li>\n</ul>\n\n<h3>Allows very readable constructs with lists</h3>\n\n<p>e.g.:</p>\n\n<pre><code>from lxml import etree\nfrom lxml.builder import E\nlst = ["alfa", "beta", "gama"]\nxml = E.root(*[E.record(itm) for itm in lst])\netree.tostring(xml, pretty_print=True)\n</code></pre>\n\n<p>resulting in:</p>\n\n<pre><code>&lt;root&gt;\n  &lt;record&gt;alfa&lt;/record&gt;\n  &lt;record&gt;beta&lt;/record&gt;\n  &lt;record&gt;gama&lt;/record&gt;\n&lt;/root&gt;\n</code></pre>\n\n<h2>Conclusions</h2>\n\n<p>I highly recommend reading lxml tutorial - it is very well written and will give you many more reasons to use this powerful library.</p>\n\n<p>The only disadvantage of lxml is, that it must be compiled. See <a href="https://stackoverflow.com/a/23141779/346478">SO answer for more tips</a> how to install lxml from wheel format package within a fraction of a second.</p>\n'}]
['https://Stackoverflow.com/questions/337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111/']