source: TOOLS/MOSAIX/update_xml.py @ 3626

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

O.M. : adding Log property

  • Property svn:keywords set to Log
File size: 4.9 KB
Line 
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##
16## SVN information
17__Author__   = "$Author: omamce $"
18__Date__     = "$Date: 2018-03-12 10:59:12 +0100 (Mon, 12 Mar 2018) $"
19__Revision__ = "$Revision: 3623 $"
20__Id__       = "$Id: update_xml.py 3623 2018-03-12 09:59:12Z omamce $"
21__Log__      = "$Log: $"
22
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 :
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>
34 -d         | --debug         : debug
35 -i <file>  | --input=<file>  : input file  (default iodef.xml)
36 -o <file>  | --output=<file> : output file (default: overwrite input file)
37 -n <file>  | --node=<file>   : node in Xpath syntax
38 -f <field> | --field=<field> : xml field to update
39 -t <text>  | --text=<text>   : will replace the 'text' part of the Xpath by <text>
40 -v <value> | --value=<value> : new value for xml field
41example : 
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
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   
48# Check version
49if sys.version_info<(2,7,0):
50  sys.stderr.write ( "You need python 2.7 or later to run this script\n" )
51  sys.exit (1)
52 
53## Input parameters
54FileIn   = 'iodef.xml'
55FileOut  = None
56Node     = None 
57Key      = None
58Text     = None
59Value    = None
60Debug    = False
61
62## Command line options
63try:
64    myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:n:k:v:t:dh', [ 'input=', 'output=', 'node=', 'key=', 'value=', 'text=', 'debug=', '--help' ] )
65except getopt.GetoptError as cmdle :
66    print ( "Command line error :", cmdle, "\n" )
67    usage ()
68    sys.exit(1)
69
70for myopt, myval in myopts :
71    if myopt in [ '-h', '--help'   ] : usage () ; sys.exit (0) ; 
72    if myopt in [ '-i', '--input'  ] : FileIn   = myval
73    if myopt in [ '-o', '--output' ] : FileOut  = myval
74    if myopt in [ '-n', '--node'   ] : Node     = myval
75    if myopt in [ '-k', '--key'    ] : Key      = myval
76    if myopt in [ '-t', '--text'   ] : Text     = myval
77    if myopt in [ '-v', '--value'  ] : Value    = myval
78    if myopt in [ '-d', '--debug'  ] : Debug    = True
79
80## Some coherency checking of command line parameters
81if FileOut == None : FileOut = FileIn
82
83if Node == None :
84    print ( "Error : please specify -n <node>", "\n" )
85    usage ()
86    sys.exit (1)
87   
88if Key == None and Text == None :
89    print ( "Error : please specify either -t <text> or -k <key> -v <value> ", "\n" )
90    usage ()
91    sys.exit (1)
92
93if Key != None and Text != None :
94    print ( "Error : please specify only one option between -t", Text, "and -k", Key, "\n" )
95    usage ()
96    sys.exit (1)
97
98if Key != None and Value == None :
99    print ( "Error : please specify -v <value> when -k", Key, "is given", "\n")
100    usage ()
101    sys.exit (1)
102   
103## Get XML tree from input file
104iodef = xml.etree.ElementTree.parse ( FileIn )
105
106## Find node
107nodeList = iodef.findall ( Node )
108
109## Check that only one node is found
110if len(nodeList) == 0 :
111    print ( "Error : node not found" )
112    print ( "Node  :", Node )
113    sys.exit(1)
114   
115if len(nodeList) > 1 :
116    print ( "Error :", len(nodeList), "occurences of node found" )
117    print ( "Node  :", Node )
118    sys.exit(1)
119
120## Update element
121elem = nodeList[0]
122
123if Debug :
124    print ( 'Node  :', Node  )
125    print ( 'Key   :', Key   )
126    print ( 'Value :', Value )
127
128if Text != None :
129    if Debug :
130        print ( 'Attributes of node:', elem.attrib )
131        print ( 'Text       :', elem.text   )
132    elem.text = Text
133
134if Key != None :
135    # To do : check that Key exist (it is added if not : do we want that ?)
136    if Debug :
137        print ( 'Attributes of node:', elem.attrib )
138    elem.attrib.update ( { Key:Value } )
139   
140
141## Writes XML tree to file
142iodef.write ( FileOut )
143
144## This is the end
145sys.exit(0)
146   
147### ===========================================================================
148###
149###                               That's all folk's !!!
150###
151### ===========================================================================
152
Note: See TracBrowser for help on using the repository browser.