-1

Ive been reading around online and came across this solution Creating a simple XML file using python but was not sure if it was still a relevant solution since the post is 5 years old. Python I'm guessing evolved a lot in the past 5 years.

I have a class which has a few attributes. In this case an attribute name which is a string and then another attribute called items which is a list of strings. I want to write this data to an xml and then later be able to parse read it back in to repopulate the variable Teams when I run a tool. I want the xml which it generates to have the pretty spacing and indentations.

Can I create the desired xml with a standard library in python as well as parse an xml file? Or do I need to use a separate download, is so what do you recommend?

Teams =[]
Teams.append(Team( name="Zebras" items=[]))
Teams.append(Team( name="Cobras" items=[]))
Teams.append(Team( name="Tigers" items=[]))
Teams.append(Team( name="Lizards" items=[]))

Xml output example

<?xml version="1.0" ?>
<teams>
  <team name="cobras">
    <item name="teapot001"/>
    <item name="teapot002"/>
    <item name="teapot003"/>
  </team>
  <team name="lizards">
    <item name="teapot001"/>
    <item name="teapot002"/>
    <item name="teapot003"/>
  </team>
</teams>
Community
  • 1
  • 1
JokerMartini
  • 5,674
  • 9
  • 83
  • 193
  • Use [`xml.etree.ElementTree`](https://docs.python.org/2/library/xml.etree.elementtree.html), or see the [Python wiki](https://wiki.python.org/moin/PythonXml) for more options. – augurar Nov 01 '15 at 18:33
  • Creating and parsing xml are different problems and may be best handled with different tools. You can create documents with ElementTree, lxml and etc... Or you could use an xml template tool such as jinga2. For simple xml documents, it's common to just write the tags manually. – tdelaney Nov 01 '15 at 18:39
  • *was not sure if it was still a relevant solution since the post is 5 years old*. The accepted answer to the linked question is still OK. Nothing significant has changed in the APIs. – mzjn Nov 02 '15 at 08:03

1 Answers1

1

Use ElementTree or minidom from xml library, you can se this answer in this post:

How do I parse XML in Python?

example:

import xml.dom.minidom

xml = xml.dom.minidom.parse(xml_fname)
# or xml.dom.minidom.parseString(xml_string)
pretty_xml_as_string = xml.toprettyxml()
Community
  • 1
  • 1
Rui Lima
  • 227
  • 1
  • 4
  • 17
  • The answer in the post doesn't address the formatting which does not contain any spaces or indents – JokerMartini Nov 01 '15 at 20:39
  • @JokerMartini I believe you could use toprettyxml method: http://stackoverflow.com/questions/749796/pretty-printing-xml-in-python – Rui Lima Nov 01 '15 at 21:07