### =========================================================================== ### ### 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: omamce $" __Date__ = "$Date: 2018-03-12 10:59:12 +0100 (Mon, 12 Mar 2018) $" __Revision__ = "$Revision: 3623 $" __Id__ = "$Id: update_xml.py 3623 2018-03-12 09:59:12Z omamce $" __Log__ = "$Log: $" # # 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 [node in Xpath syntax] -k -v python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n [node in Xpath syntax] -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 -t | --text= : will replace the 'text' part of the Xpath by -v | --value= : new value for xml field 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 if sys.version_info<(2,7,0): sys.stderr.write ( "You need python 2.7 or later to run this script\n" ) sys.exit (1) ## 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, "\n" ) 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 if FileOut == None : FileOut = FileIn if Node == None : print ( "Error : please specify -n ", "\n" ) usage () sys.exit (1) if Key == None and Text == None : print ( "Error : please specify either -t or -k -v ", "\n" ) usage () sys.exit (1) if Key != None and Text != None : print ( "Error : please specify only one option between -t", Text, "and -k", Key, "\n" ) usage () sys.exit (1) if Key != None and Value == None : print ( "Error : please specify -v when -k", Key, "is given", "\n") usage () sys.exit (1) ## Get XML tree from input file iodef = xml.etree.ElementTree.parse ( FileIn ) ## Find node nodeList = iodef.findall ( Node ) ## Check that 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:', elem.attrib ) print ( 'Text :', 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:', 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 !!! ### ### ===========================================================================