1 #!/usr/bin/env python 2 3 """ 4 Utility functions for XSLForms documents. 5 6 Copyright (C) 2005 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU Lesser General Public License as published by the Free 10 Software Foundation; either version 3 of the License, or (at your option) any 11 later version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more 16 details. 17 18 You should have received a copy of the GNU Lesser General Public License along 19 with this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 def add_elements(positions, *element_names): 23 24 """ 25 At the specified 'positions' in a document, add a new element using the 26 first of the given 'element_names' inside any subsequent element named in 27 the 'element_names' list, in turn creating new parent elements for each 28 element name found. 29 """ 30 31 if not positions: 32 return 33 reversed_element_names = list(element_names)[:] 34 reversed_element_names.reverse() 35 for position in positions: 36 element = position 37 for element_name in reversed_element_names[:-1]: 38 found_elements = element.xpath(element_name) 39 if not found_elements: 40 new_element = element.ownerDocument.createElementNS(None, element_name) 41 element.appendChild(new_element) 42 else: 43 new_element = found_elements[0] 44 element = new_element 45 new_element = element.ownerDocument.createElementNS(None, reversed_element_names[-1]) 46 element.appendChild(new_element) 47 48 def remove_elements(positions): 49 50 """ 51 Remove the elements located at the given 'positions'. 52 """ 53 54 if not positions: 55 return 56 for position in positions: 57 position.parentNode.removeChild(position) 58 59 # vim: tabstop=4 expandtab shiftwidth=4