|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
AT&T devCentral & BlackBerry(r) Webcast Series: BlackBerry and GPS -Build Location Awareness into your BlackBerry Applications, July 10th-1:00PM EST. Register Today!
|
|
#1
|
|||
|
|||
|
adding info to xml files
###########################
import xml.dom.minidom from xml.dom.minidom import getDOMImplementation output = open("book1.xml", "w") impl = getDOMImplementation() newdoc = impl.createDocument(None, "library", None) book = newdoc.createElement("book") newdoc.documentElement.appendChild(book) chapter = newdoc.createElement("chapter") book.appendChild(chapter) page = newdoc.createElement("page") pageContent = newdoc.createTextNode("somerandomtext") page.appendChild(pageContent) chapter.appendChild(page) output.writelines(newdoc.toprettyxml()) ######################### after i create the xml file... how can i retrieve it and add some info to it... for example how can i add another page to chapter... or another chapter to book...any help would be greatly appreciated... |
|
#2
|
|||
|
|||
|
I think this code will add a chapter to your book.
Code:
import xml.dom.minidom
doc = xml.dom.minidom.parse("book1.xml")
book = doc.getElementsByTagName("book")[0]
newChapter = doc.createElement("chapter")
book.appendChild(newChapter)
newDoc = doc.toprettyxml()
fh = open("book1.xml", "w")
fh.write(newDoc)
fh.close()
There is also an insertBefore function you can use to insert the chapter before an existing chapter. Code:
chapters = doc.getElementsByTagName("chapter")
newChapter = doc.createElement("chapter")
book.insertBefore(newChapter, chapters[3])
This will insert the new chapter before the 4th chapter. There is one thing I don't like about the toprettyxml function. If you open a "pretty" xml document and prints it back to the file with toprettyxml, it adds the prettyfying whitespace one more time so you get twice as much whitespace as you want. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > adding info to xml files |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|