简体   繁体   中英

Append element with SAX in python

I know how to parse xml with sax in python, but how would I go about inserting elements into the document i'm parsing? Do I have to create a separate file?

Could someone provide a simple example or alter the one I've put below. Thanks.


from xml.sax.handler import ContentHandler
from xml.sax import make_parser
import sys

class aHandler(ContentHandler):

    def startElement(self, name, attrs):
        print "<",name,">"

    def characters(self, content):
        print content

    def endElement(self,name):
        print "</",name,">"


handler = aHandler()
saxparser = make_parser()
saxparser.setContentHandler(handler)

datasource = open("settings.xml","r")
saxparser.parse(datasource)

<?xml version="1.0"?>
<names>
    <name>
      <first>First1</first>
      <second>Second1</second>
    </name>
    <name>
      <first>First2</first>
      <second>Second2</second>
    </name>
    <name>
      <first>First3</first>
      <second>Second3</second>
    </name>
</names>

With DOM, you have the entire xml structure in memory.
With SAX, you don't have a DOM available, so you don't have anything to append an element to.

The main reason for using SAX is if the xml structure is really, really huge-- if it would be a serious performance hit to place the DOM in memory. If that isn't the case (as it appears to be from your small sample xml file), I would always use DOM vs. SAX.

If you go the DOM route, (which seems to be the only option to me), look into lxml . It's one of the best python xml libraries around.

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