首页 > 代码库 > Python,ElementTree模块处理XML时注释无法读取和保存的问题

Python,ElementTree模块处理XML时注释无法读取和保存的问题

from xml.etree import ElementTree

class CommentedTreeBuilder ( ElementTree.XMLTreeBuilder ):

    def __init__ ( self, html = 0, target = None ):

        ElementTree.XMLTreeBuilder.__init__( self, html, target )

        self._parser.CommentHandler = self.handle_comment

   

    def handle_comment ( self, data ):

        self._target.start( ElementTree.Comment, {} )

        self._target.data( data )

        self._target.end( ElementTree.Comment )

 

#示例:

xml = ElementTree.parse( rc:\test.xml, parser = CommentedTreeBuilder() )

ElementTree.dump( xml )

#如果不加这个Handler,则读取和保存时注释会自动去掉(stripped out)