Project

General

Profile

« Previous | Next » 

Revision 3331

xml_dom.py: Moved merge_adjacent() recursion and name checking into merge() so that other callers of merge() can take advantage of it, too. Added merge_by_name() and use it in merge_same_name(). Removed now-unused merge_adjacent().

View differences:

lib/xml_dom.py
244 244
    return children
245 245

  
246 246
def merge(from_, into):
247
    '''The into node is saved; the from_ node is deleted.'''
247
    '''Merges two nodes of the same tag name and their newly-adjacent children.
248
    @post The into node is saved; the from_ node is deleted.
249
    '''
250
    if from_ == None or into == None: return # base case
251
    if from_.tagName != into.tagName: return # not mergeable
252
    
253
    from_first = from_.firstChild # save before merge
248 254
    for child in NodeIter(from_): into.appendChild(child)
249 255
    remove(from_)
250

  
251
def merge_adjacent(node):
252
    '''Repeatedly merges a node with its siblings as long as they or their
253
    newly-adjacent children have the same tag name'''
254
    if node == None: return # base case
255 256
    
256
    for node_, next in [(node.previousSibling, node), (node, node.nextSibling)]:
257
        if node_ != None and next != None and node_.tagName == next.tagName:
258
            next_first = next.firstChild # save before merge
259
            merge(next, node_)
260
            merge_adjacent(next_first) # previousSibling is now node_.lastChild
257
    # Recurse
258
    merge(from_first, from_first.previousSibling) # = into.lastChild
261 259

  
260
def merge_by_name(root, name):
261
    '''Merges siblings in root with the given name'''
262
    children = by_tag_name(root, name)
263
    child0 = children.pop(0)
264
    for child in children: merge(child, child0)
265

  
262 266
def merge_same_name(node):
263
    '''Merges nodes with the same name as a node, using merge_adjacent()'''
264
    for node_ in by_tag_name(node.parentNode, node.tagName):
265
        if node_ is node: continue # not self
266
        merge_adjacent(node_)
267
    '''Merges nodes with the same name as a node'''
268
    merge_by_name(node.parentNode, node.tagName)
267 269

  
268 270
##### XML documents
269 271

  

Also available in: Unified diff