#!/usr/bin/env python ### =========================================================================== ### ### Modifies or add an element in an XML file ### ### =========================================================================== ## ## Warning, to install, configure, run, use any of Olivier Marti's ## software or to read the associated documentation you'll need at least ## one (1) brain in a reasonably working order. Lack of this implement ## will void any warranties (either express or implied). ## O. Marti assumes no responsability for errors, omissions, ## data loss, or any other consequences caused directly or indirectly by ## the usage of his software by incorrectly or partially configured ## personal. ## ## SVN information __Author__ = "$Author$" __Date__ = "$Date$" __Revision__ = "$Revision$" __Id__ = "$Id$" __HeadURL = "$HeadURL$" # # Tested with python/2.7.12 and python/3.6.4 # import xml.etree.ElementTree import argparse, sys, textwrap # Check version of Python Version = sys.version_info if Version < (2,7,0) : sys.stderr.write ( "You need python 2.7 or later to run this script\n" ) sys.stderr.write ( "Present version is: " + str(Version[0]) + "." + str(Version[1]) + "." + str(Version[2]) + "\n" ) sys.exit (1) # Creating a parser to read the command line arguments # The first step in using the argparse is creating an ArgumentParser object: parser = argparse.ArgumentParser (description = """ examples : python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="file_src"]/field[@id="mask_source"]' -k name -v maskutil_T python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]' -t dstDomainType python %(prog)s -i iodef.xml -e commands.txt (not implemented yet) """ + "\n" + "SVN : " + __Revision__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='-------- This is the end of the help message --------') # Adding arguments group1 = parser.add_mutually_exclusive_group (required=True) parser.add_argument ( '-i', '--input' , help="input file" , default='iodef.xml', type=str, metavar='' ) parser.add_argument ( '-o', '--output' , help="output file" , default=None , type=str, metavar='' ) parser.add_argument ( '-n', '--node' , help="xml node in Xpath syntax", default=None, required=True, type=str, metavar='') group1.add_argument ( '-k', '--key' , help="xml key to update" , default=None , type=str , metavar='' ) group1.add_argument ( '-t', '--text' , help="will replace the 'text' part of the Xpath by ", default=None, type=str, metavar='' ) parser.add_argument ( '-v', '--value' , help="new value for xml key", default=None, type=str, metavar='' ) parser.add_argument ( '-d', '--debug' , action="store_true", default=False ) parser.add_argument ( '-V', '--verbose', action="store_true", default=False ) # Parse command line myargs = parser.parse_args() Verbose = myargs.verbose if Verbose : print ( "Command line arguments : " , myargs ) FileIn = myargs.input FileOut = myargs.output Node = myargs.node Key = myargs.key Text = myargs.text Value = myargs.value Debug = myargs.debug # Error handling not dealed by argparse if Key != None and Value == None : print ( "Error. When -k|--key= is specified, you must specify -v|--value=" ) sys.exit (-1) if FileOut == None : FileOut = FileIn # Remove whitespaces at both ends Node = Node.rstrip().lstrip() ## Get XML tree from input file iodef = xml.etree.ElementTree.parse ( FileIn ) ## Find node nodeList = iodef.findall ( Node ) ## Check that one and only one node is found if len (nodeList) == 0 : print ( "Error : node not found" ) print ( "Node : " + Node ) sys.exit (1) if len (nodeList) > 1 : print ( "Error : " + len (nodeList)+" occurences of node found" ) print ( "Node : " + Node ) sys.exit (2) ## Update element elem = nodeList[0] if Debug : print ( 'Node : ' + Node ) print ( 'Key : ' + Key ) print ( 'Value : ' + Value ) if Text != None : if Debug : print ( 'Attributes of node: ' + str (elem.attrib) ) print ( 'Text : ' + str (elem.text) ) elem.text = Text if Key != None : # To do : check that Key exist (it is added if not : do we want that ?) if Debug : print ( 'Attributes of node: ' + str (elem.attrib) ) elem.attrib.update ( { Key:Value } ) ## Writes XML tree to file iodef.write ( FileOut ) ## This is the end sys.exit (0) ### =========================================================================== ### ### That's all folk's !!! ### ### ===========================================================================