source: TOOLS/MOSAIX/update_xml.py @ 4049

Last change on this file since 4049 was 3671, checked in by omamce, 6 years ago

O.M. : beautify, and more help

  • Property svn:keywords set to Date Revision HeadURL Author Id
File size: 5.1 KB
RevLine 
[3620]1### ===========================================================================
2###
3### Modifies or add an element in an XML file
4###
5### ===========================================================================
6##
7##  Warning, to install, configure, run, use any of Olivier Marti's
8##  software or to read the associated documentation you'll need at least
9##  one (1) brain in a reasonably working order. Lack of this implement
10##  will void any warranties (either express or implied).
11##  O. Marti assumes no responsability for errors, omissions,
12##  data loss, or any other consequences caused directly or indirectly by
13##  the usage of his software by incorrectly or partially configured
14##  personal.
15##
[3623]16## SVN information
[3665]17__Author__   = "$Author$"
18__Date__     = "$Date$"
19__Revision__ = "$Revision$"
20__Id__       = "$Id$"
[3633]21__HeadURL    = "$HeadURL$"
[3623]22
[3620]23#
24# Tested with python/2.7.12 and python/3.6.4
25#
26import xml.etree.ElementTree
27import getopt, sys
28
29##
30def usage () :
31    texte = """%(prog)s usage :
[3671]32python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n <node in Xpath syntax> -k <key>  -v <value>
33python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n <node in Xpath syntax> -t <value>
[3620]34 -d         | --debug         : debug
[3671]35 -i <file>  | --input=<file>  : input file  (default: iodef.xml)
[3620]36 -o <file>  | --output=<file> : output file (default: overwrite input file)
[3671]37 -n <node>  | --node=<node>   : node in Xpath syntax
[3620]38 -f <field> | --field=<field> : xml field to update
[3671]39 -v <value> | --value=<value> : new value for xml field
[3620]40 -t <text>  | --text=<text>   : will replace the 'text' part of the Xpath by <text>
41example : 
[3671]42    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
[3620]43    """
44    #print ( texte % ( sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0] ) )
45    #print ( texte %   ( 6*[sys.argv[0]] ))
46    print ( texte % { 'prog':sys.argv[0] } )
47   
[3671]48# Check version of Python
49Version = sys.version_info
50if Version < (2,7,0) :
[3620]51  sys.stderr.write ( "You need python 2.7 or later to run this script\n" )
[3671]52  sys.stderr.write ( "Present version is: " + str(Version[0]) + "." + str(Version[1]) + "." + str(Version[2]) + "\n" )
[3620]53  sys.exit (1)
54 
[3671]55## Default input parameters
[3620]56FileIn   = 'iodef.xml'
57FileOut  = None
58Node     = None 
59Key      = None
60Text     = None
61Value    = None
62Debug    = False
63
64## Command line options
65try:
66    myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:n:k:v:t:dh', [ 'input=', 'output=', 'node=', 'key=', 'value=', 'text=', 'debug=', '--help' ] )
67except getopt.GetoptError as cmdle :
[3671]68    print ( "Command line error : "+cmdle )
[3620]69    usage ()
70    sys.exit(1)
71
72for myopt, myval in myopts :
73    if myopt in [ '-h', '--help'   ] : usage () ; sys.exit (0) ; 
74    if myopt in [ '-i', '--input'  ] : FileIn   = myval
75    if myopt in [ '-o', '--output' ] : FileOut  = myval
76    if myopt in [ '-n', '--node'   ] : Node     = myval
77    if myopt in [ '-k', '--key'    ] : Key      = myval
78    if myopt in [ '-t', '--text'   ] : Text     = myval
79    if myopt in [ '-v', '--value'  ] : Value    = myval
80    if myopt in [ '-d', '--debug'  ] : Debug    = True
81
82## Some coherency checking of command line parameters
[3671]83ErrorCount = 0
[3620]84
[3671]85if FileIn == None :
86    print ( "Error : please specify input file by -i <file>" )
87    ErrorCount += 1
88
[3620]89if Node == None :
[3671]90    print ( "Error : please specify -n <node>" )
91    ErrorCount += 1
[3620]92   
93if Key == None and Text == None :
[3671]94    print ( "Error : please specify either -t <text> or -k <key> -v <value>" )
95    ErrorCount += 1
[3620]96
97if Key != None and Text != None :
[3671]98    print ( "Error : please specify only one option between -t "+Text+" and -k "+Key )
99    ErrorCount += 1
[3620]100
101if Key != None and Value == None :
[3671]102    print ( "Error : please specify -v <value> when -k "+Key+" is given")
103    ErrorCount += 1
104 
105if ErrorCount > 0 :
[3620]106    usage ()
107    sys.exit (1)
[3671]108
109if FileOut == None : FileOut = FileIn
[3620]110   
111## Get XML tree from input file
112iodef = xml.etree.ElementTree.parse ( FileIn )
113
114## Find node
115nodeList = iodef.findall ( Node )
116
[3671]117## Check that one and only one node is found
[3620]118if len(nodeList) == 0 :
119    print ( "Error : node not found" )
[3671]120    print ( "Node  : "+Node )
121    sys.exit (1)
[3620]122   
123if len(nodeList) > 1 :
[3671]124    print ( "Error : "+len(nodeList)+" occurences of node found" )
125    print ( "Node  : "+Node )
126    sys.exit (1)
[3620]127
128## Update element
129elem = nodeList[0]
130
131if Debug :
[3671]132    print ( 'Node  : '+Node  )
133    print ( 'Key   : '+Key   )
134    print ( 'Value : '+Value )
[3620]135
136if Text != None :
137    if Debug :
[3671]138        print ( 'Attributes of node: '+str(elem.attrib) )
139        print ( 'Text              : '+str(elem.text)   )
[3620]140    elem.text = Text
141
142if Key != None :
143    # To do : check that Key exist (it is added if not : do we want that ?)
144    if Debug :
[3671]145        print ( 'Attributes of node: '+str(elem.attrib) )
[3620]146    elem.attrib.update ( { Key:Value } )
147   
148
149## Writes XML tree to file
150iodef.write ( FileOut )
151
152## This is the end
[3671]153sys.exit (0)
[3620]154   
155### ===========================================================================
156###
157###                               That's all folk's !!!
158###
159### ===========================================================================
160
Note: See TracBrowser for help on using the repository browser.