0

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>
2
  • 1
    Why would you put yourself through the pain and suffering of minidom when ElementTree exists? (Also, class:=memory, unlike class='memory', is not valid XML) Commented Mar 19, 2012 at 16:44
  • <p></p> is an XML element and needs to be created when using minidom... which you shouldn't use anyway. see @CharlesDuffy comment above. Commented Mar 19, 2012 at 16:48

1 Answer 1

2

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 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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.