简体   繁体   中英

Issue in generating the xml file from python minidom

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>

You need two quick changes

  1. Create a p element eg doc.createElement('p')
  2. Don't set attributes manually instead use node.attributes eg 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 eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM