### =========================================================================== ### ### 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 getopt, sys ## def usage () : texte = """%(prog)s usage : python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n -k -v python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n -t -d | --debug : debug -i | --input= : input file (default: iodef.xml) -o | --output= : output file (default: overwrite input file) -n | --node= : node in Xpath syntax -f | --field= : xml field to update -v | --value= : new value for xml field -t | --text= : will replace the 'text' part of the Xpath by example : 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 """ #print ( texte % ( sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0] ) ) #print ( texte % ( 6*[sys.argv[0]] )) print ( texte % { 'prog':sys.argv[0] } ) # 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) ## Default input parameters FileIn = 'iodef.xml' FileOut = None Node = None Key = None Text = None Value = None Debug = False ## Command line options try: myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:n:k:v:t:dh', [ 'input=', 'output=', 'node=', 'key=', 'value=', 'text=', 'debug=', '--help' ] ) except getopt.GetoptError as cmdle : print ( "Command line error : "+cmdle ) usage () sys.exit(1) for myopt, myval in myopts : if myopt in [ '-h', '--help' ] : usage () ; sys.exit (0) ; if myopt in [ '-i', '--input' ] : FileIn = myval if myopt in [ '-o', '--output' ] : FileOut = myval if myopt in [ '-n', '--node' ] : Node = myval if myopt in [ '-k', '--key' ] : Key = myval if myopt in [ '-t', '--text' ] : Text = myval if myopt in [ '-v', '--value' ] : Value = myval if myopt in [ '-d', '--debug' ] : Debug = True ## Some coherency checking of command line parameters ErrorCount = 0 if FileIn == None : print ( "Error : please specify input file by -i " ) ErrorCount += 1 if Node == None : print ( "Error : please specify -n " ) ErrorCount += 1 if Key == None and Text == None : print ( "Error : please specify either -t or -k -v " ) ErrorCount += 1 if Key != None and Text != None : print ( "Error : please specify only one option between -t "+Text+" and -k "+Key ) ErrorCount += 1 if Key != None and Value == None : print ( "Error : please specify -v when -k "+Key+" is given") ErrorCount += 1 if ErrorCount > 0 : usage () sys.exit (1) if FileOut == None : FileOut = FileIn ## 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 (1) ## 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 !!! ### ### ===========================================================================