source: TOOLS/MOSAIX/update_xml.py @ 3642

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

O.M. : continue with propset

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