source: TOOLS/MOSAIX/update_xml.py @ 3620

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

O.M. : continue first commit

File size: 4.7 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#
17__version__ = "0.1"
18#
19# Tested with python/2.7.12 and python/3.6.4
20#
21import xml.etree.ElementTree
22import getopt, sys
23
24##
25def usage () :
26    texte = """%(prog)s usage :
27python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n [node in Xpath syntax] -k <key>  -v <value>
28python %(prog)s [-d] [-i iodef.xml] [-o iodef_new.xml] -n [node in Xpath syntax] -t <value>
29 -d         | --debug         : debug
30 -i <file>  | --input=<file>  : input file  (default iodef.xml)
31 -o <file>  | --output=<file> : output file (default: overwrite input file)
32 -n <file>  | --node=<file>   : node in Xpath syntax
33 -f <field> | --field=<field> : xml field to update
34 -t <text>  | --text=<text>   : will replace the 'text' part of the Xpath by <text>
35 -v <value> | --value=<value> : new value for xml field
36example : 
37    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
38    """
39    #print ( texte % ( sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0] ) )
40    #print ( texte %   ( 6*[sys.argv[0]] ))
41    print ( texte % { 'prog':sys.argv[0] } )
42   
43# Check version
44if sys.version_info<(2,7,0):
45  sys.stderr.write ( "You need python 2.7 or later to run this script\n" )
46  sys.exit (1)
47 
48## Input parameters
49FileIn   = 'iodef.xml'
50FileOut  = None
51Node     = None 
52Key      = None
53Text     = None
54Value    = None
55Debug    = False
56
57## Command line options
58try:
59    myopts, myargs = getopt.getopt ( sys.argv[1:], 'i:o:n:k:v:t:dh', [ 'input=', 'output=', 'node=', 'key=', 'value=', 'text=', 'debug=', '--help' ] )
60except getopt.GetoptError as cmdle :
61    print ( "Command line error :", cmdle, "\n" )
62    usage ()
63    sys.exit(1)
64
65for myopt, myval in myopts :
66    if myopt in [ '-h', '--help'   ] : usage () ; sys.exit (0) ; 
67    if myopt in [ '-i', '--input'  ] : FileIn   = myval
68    if myopt in [ '-o', '--output' ] : FileOut  = myval
69    if myopt in [ '-n', '--node'   ] : Node     = myval
70    if myopt in [ '-k', '--key'    ] : Key      = myval
71    if myopt in [ '-t', '--text'   ] : Text     = myval
72    if myopt in [ '-v', '--value'  ] : Value    = myval
73    if myopt in [ '-d', '--debug'  ] : Debug    = True
74
75## Some coherency checking of command line parameters
76if FileOut == None : FileOut = FileIn
77
78if Node == None :
79    print ( "Error : please specify -n <node>", "\n" )
80    usage ()
81    sys.exit (1)
82   
83if Key == None and Text == None :
84    print ( "Error : please specify either -t <text> or -k <key> -v <value> ", "\n" )
85    usage ()
86    sys.exit (1)
87
88if Key != None and Text != None :
89    print ( "Error : please specify only one option between -t", Text, "and -k", Key, "\n" )
90    usage ()
91    sys.exit (1)
92
93if Key != None and Value == None :
94    print ( "Error : please specify -v <value> when -k", Key, "is given", "\n")
95    usage ()
96    sys.exit (1)
97   
98## Get XML tree from input file
99iodef = xml.etree.ElementTree.parse ( FileIn )
100
101## Find node
102nodeList = iodef.findall ( Node )
103
104## Check that only one node is found
105if len(nodeList) == 0 :
106    print ( "Error : node not found" )
107    print ( "Node  :", Node )
108    sys.exit(1)
109   
110if len(nodeList) > 1 :
111    print ( "Error :", len(nodeList), "occurences of node found" )
112    print ( "Node  :", Node )
113    sys.exit(1)
114
115## Update element
116elem = nodeList[0]
117
118if Debug :
119    print ( 'Node  :', Node  )
120    print ( 'Key   :', Key   )
121    print ( 'Value :', Value )
122
123if Text != None :
124    if Debug :
125        print ( 'Attributes of node:', elem.attrib )
126        print ( 'Text       :', elem.text   )
127    elem.text = Text
128
129if Key != None :
130    # To do : check that Key exist (it is added if not : do we want that ?)
131    if Debug :
132        print ( 'Attributes of node:', elem.attrib )
133    elem.attrib.update ( { Key:Value } )
134   
135
136## Writes XML tree to file
137iodef.write ( FileOut )
138
139## This is the end
140sys.exit(0)
141   
142### ===========================================================================
143###
144###                               That's all folk's !!!
145###
146### ===========================================================================
147
Note: See TracBrowser for help on using the repository browser.