Issue in generating the xml file from python minidom
Question: Here is the code:

    
    
        from xml.dom.minidom import Document
    
    doc = Document()
    root = doc.createElement('root')
    doc.appendChild(root)
    for i in range(1,3):
        main = doc.createElement('item class:=memory')
        root.appendChild(main)
        for j in range(1,3):
            text = doc.createTextNode('DIMM Size'+str(j))
            main.appendChild(text)
    
    print (doc.toprettyxml(indent='\t'))
    

Here is the output:

    
    
         <?xml version="1.0" ?>
    <root>
        <item class:=memory>
            DIMM Size1
            DIMM Size2
        </item class:=memory>
        <item class:=memory>
            DIMM Size1
            DIMM Size2
        </item class:=memory>
    </root>
    

I am trying to generate the file with following code. Is there a way to
generate the following output:

    
    
    <root>
        <item class:=memory>
            <p> DIMM Size1 </p>
            <p>DIMM Size2 </p>
        </item>
        <item class:=memory>
            <p>DIMM Size1</p>
            <p>DIMM Size2</p>
        </item>
    </root>
    


Answer: You need two quick changes

  1. Create a `p` element e.g. `doc.createElement('p')`
  2. Don't set attributes manually instead use node.attributes e.g. `main.attributes['class']='memory'`

so your code should look like this

    
    
    from xml.dom.minidom import Document
    
    doc = Document()
    root = doc.createElement('root')
    doc.appendChild(root)
    for i in range(1,3):
        main = doc.createElement('item')
        main.attributes['class']='memory'
        root.appendChild(main)
        for j in range(1,3):
            p = doc.createElement('p')
            text = doc.createTextNode('DIMM Size'+str(j))
            p.appendChild(text)
            main.appendChild(p)
    
    print (doc.toprettyxml(indent='\t'))
    

A long term change would be to use
[ElementTree](http://docs.python.org/library/xml.etree.elementtree.html) which
has more intuitive interface and is easy to use, more so while reading xml
e.g. your example in element tree

    
    
    from xml.etree import cElementTree as etree
    
    root = etree.Element('root')
    for i in range(1,3):
        item = etree.SubElement(root, 'item')
        item.attrib['class']='memory'
        for j in range(1,3):
            p = etree.SubElement(item, 'p')
            p.text = 'DIMM Size %s'%j
    
    print etree.tostring(root)
    

