#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2004
    Posts
    10
    Rep Power
    0

    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. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2003
    Location
    Norway
    Posts
    41
    Rep Power
    12
    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.
    Good web hosting info - articles about web hosting
    hb's web dev blog

IMN logo majestic logo threadwatch logo seochat tools logo