以下是代码:
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'))
这是输出:
<?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>
我正在尝试使用以下代码生成文件。有没有办法生成以下输出:
<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>
答案 0 :(得分:2)
您需要两次快速更改
p
元素,例如doc.createElement('p')
main.attributes['class']='memory'
所以你的代码应该是这样的
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'))
长期的改变是使用ElementTree,它具有更直观的界面并且易于使用,在阅读xml时更是如此。您在元素树中的示例
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)