首页 > 代码库 > 【Python Network】使用DOM生成XML
【Python Network】使用DOM生成XML
单纯的为DOM树添加结点。
1 #!/usr/bin/env python 2 # Generating XML with DOM - Chapter 8 - domgensample.py 3 4 from xml.dom import minidom, Node 5 6 doc = minidom.Document() 7 8 doc.appendChild(doc.createComment("Sample XML Document - Chapter 8 -")) 9 10 # Generate book 11 book = doc.createElement(‘book‘) 12 doc.appendChild(book) 13 14 # The title 15 title = doc.createElement(‘title‘) 16 title.appendChild(doc.createTextNode(‘Sample XML Thing‘)) 17 book.appendChild(title) 18 19 # The author section 20 author = doc.createElement(‘author‘) 21 book.appendChild(author) 22 name = doc.createElement(‘name‘) 23 author.appendChild(name) 24 firstname = doc.createElement(‘first‘) 25 name.appendChild(firstname) 26 firstname.appendChild(doc.createTextNode(‘Benjamin‘)) 27 name.appendChild(doc.createTextNode(‘ ‘)) 28 lastname = doc.createElement(‘last‘) 29 name.appendChild(lastname) 30 lastname.appendChild(doc.createTextNode(‘Smith‘)) 31 32 affiliation = doc.createElement(‘affiliation‘) 33 author.appendChild(affiliation) 34 affiliation.appendChild(doc.createTextNode(‘Spring Widgets, Inc.‘)) 35 36 # The chapter 37 chapter = doc.createElement(‘chapter‘) 38 book.appendChild(chapter) 39 chapter.setAttribute(‘number‘, ‘1‘) 40 title = doc.createElement(‘title‘) 41 chapter.appendChild(title) 42 title.appendChild(doc.createTextNode(‘First Chapter‘)) 43 44 para = doc.createElement(‘para‘) 45 chapter.appendChild(para) 46 para.appendChild(doc.createTextNode("I think widgets are great. You" + " should buy lots of them from ")) 47 company = doc.createElement(‘company‘) 48 para.appendChild(company) 49 company.appendChild(doc.createTextNode(‘Spring Widgets, Inc‘)) 50 51 para.appendChild(doc.createTextNode(‘.‘)) 52 53 print doc.toprettyxml(indent = ‘ ‘)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。