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 library is free software; you can redistribute it and/or 9 modify it under the terms of the GNU Lesser General Public 10 License as published by the Free Software Foundation; either 11 version 2.1 of the License, or (at your option) any later version. 12 13 This library is distributed in the hope that it will be useful, 14 but WITHOUT ANY WARRANTY; without even the implied warranty of 15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 Lesser General Public License for more details. 17 18 You should have received a copy of the GNU Lesser General Public 19 License along with this library; if not, write to the Free Software 20 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA 21 """ 22 23 def add_elements(positions, *element_names): 24 25 """ 26 At the specified 'positions' in a document, add a new element using the 27 first of the given 'element_names' inside any subsequent element named in 28 the 'element_names' list, in turn creating new parent elements for each 29 element name found. 30 """ 31 32 if not positions: 33 return 34 reversed_element_names = list(element_names)[:] 35 reversed_element_names.reverse() 36 for position in positions: 37 element = position 38 for element_name in reversed_element_names[:-1]: 39 found_elements = element.xpath(element_name) 40 if not found_elements: 41 new_element = element.ownerDocument.createElementNS(None, element_name) 42 element.appendChild(new_element) 43 else: 44 new_element = found_elements[0] 45 element = new_element 46 new_element = element.ownerDocument.createElementNS(None, reversed_element_names[-1]) 47 element.appendChild(new_element) 48 49 def remove_elements(positions): 50 51 """ 52 Remove the elements located at the given 'positions'. 53 """ 54 55 if not positions: 56 return 57 for position in positions: 58 position.parentNode.removeChild(position) 59 60 # vim: tabstop=4 expandtab shiftwidth=4