source: TOOLS/MOSAIX/update_xml.py @ 6031

Last change on this file since 6031 was 5920, checked in by omamce, 3 years ago

O.M. : small typo correction

  • Property svn:keywords set to Date Revision HeadURL Author Id
File size: 4.8 KB
RevLine 
[5916]1#!/usr/bin/env python
[3620]2### ===========================================================================
3###
4### Modifies or add an element in an XML file
5###
6### ===========================================================================
7##
8##  Warning, to install, configure, run, use any of Olivier Marti's
9##  software or to read the associated documentation you'll need at least
10##  one (1) brain in a reasonably working order. Lack of this implement
11##  will void any warranties (either express or implied).
12##  O. Marti assumes no responsability for errors, omissions,
13##  data loss, or any other consequences caused directly or indirectly by
14##  the usage of his software by incorrectly or partially configured
15##  personal.
16##
[3623]17## SVN information
[3665]18__Author__   = "$Author$"
19__Date__     = "$Date$"
20__Revision__ = "$Revision$"
21__Id__       = "$Id$"
[3633]22__HeadURL    = "$HeadURL$"
[3623]23
[3620]24#
25# Tested with python/2.7.12 and python/3.6.4
26#
27import xml.etree.ElementTree
[5916]28import argparse, sys, textwrap
[3620]29   
[3671]30# Check version of Python
31Version = sys.version_info
32if Version < (2,7,0) :
[3620]33  sys.stderr.write ( "You need python 2.7 or later to run this script\n" )
[3671]34  sys.stderr.write ( "Present version is: " + str(Version[0]) + "." + str(Version[1]) + "." + str(Version[2]) + "\n" )
[3620]35  sys.exit (1)
36 
[5916]37# Creating a parser to read the command line arguments
38# The first step in using the argparse is creating an ArgumentParser object:
39parser = argparse.ArgumentParser (description = """
40examples :
41     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
42     python %(prog)s -i iodef.xml -n 'context[@id="interpol_run"]/file_definition/file[@id="dia"]/variable[@name="dest_grid"]'   -t dstDomainType
43     python %(prog)s -i iodef.xml -e commands.txt (not implemented yet)
44   """ + "\n" + "SVN : " + __Revision__, formatter_class=argparse.RawDescriptionHelpFormatter, epilog='-------- This is the end of the help message --------')
[3620]45
[5916]46# Adding arguments
47group1 = parser.add_mutually_exclusive_group (required=True)
[3620]48
[5916]49parser.add_argument ( '-i', '--input'  , help="input file"            , default='iodef.xml', type=str, metavar='<input_file>' )
50parser.add_argument ( '-o', '--output' , help="output file"           , default=None       , type=str, metavar='<output_file>'  )
51parser.add_argument ( '-n', '--node'   , help="xml node in Xpath syntax", default=None, required=True, type=str, metavar='<xml_node>')
52group1.add_argument ( '-k', '--key'    , help="xml key to update"     , default=None , type=str , metavar='<xml_key>' )
53group1.add_argument ( '-t', '--text'   , help="will replace the 'text' part of the Xpath by <text>", default=None, type=str, metavar='<text>' )
54parser.add_argument ( '-v', '--value'  , help="new value for xml key", default=None, type=str, metavar='<value>' )
55parser.add_argument ( '-d', '--debug'  , action="store_true", default=False )
56parser.add_argument ( '-V', '--verbose', action="store_true", default=False )
[3620]57
[5916]58# Parse command line
59myargs = parser.parse_args()
60Verbose  = myargs.verbose
[3620]61
[5916]62if Verbose : print ( "Command line arguments : " , myargs )
[3671]63
[5916]64FileIn   = myargs.input
65FileOut  = myargs.output
66Node     = myargs.node
67Key      = myargs.key
68Text     = myargs.text
69Value    = myargs.value
70Debug    = myargs.debug
[3620]71
[5916]72# Error handling not dealed by argparse
[3620]73if Key != None and Value == None :
[5916]74    print ( "Error. When -k|--key=<key> is specified, you must specify -v|--value=<xml_value>" )
[5920]75    sys.exit (-1)
[3671]76
77if FileOut == None : FileOut = FileIn
[4153]78
[5916]79# Remove whitespaces at both ends
[4153]80Node = Node.rstrip().lstrip()
81
[3620]82## Get XML tree from input file
83iodef = xml.etree.ElementTree.parse ( FileIn )
84
85## Find node
86nodeList = iodef.findall ( Node )
87
[3671]88## Check that one and only one node is found
[5916]89if len (nodeList) == 0 :
[3620]90    print ( "Error : node not found" )
[5916]91    print ( "Node  : " + Node )
[3671]92    sys.exit (1)
[3620]93   
[5916]94if len (nodeList) > 1 :
95    print ( "Error : " + len (nodeList)+" occurences of node found" )
96    print ( "Node  : " + Node )
97    sys.exit (2)
[3620]98
99## Update element
100elem = nodeList[0]
101
102if Debug :
[5916]103    print ( 'Node  : ' + Node  )
104    print ( 'Key   : ' + Key   )
105    print ( 'Value : ' + Value )
[3620]106
107if Text != None :
108    if Debug :
[5916]109        print ( 'Attributes of node: ' + str (elem.attrib) )
110        print ( 'Text              : ' + str (elem.text)   )
[3620]111    elem.text = Text
112
113if Key != None :
114    # To do : check that Key exist (it is added if not : do we want that ?)
115    if Debug :
[5916]116        print ( 'Attributes of node: ' + str (elem.attrib) )
[3620]117    elem.attrib.update ( { Key:Value } )
118   
119## Writes XML tree to file
120iodef.write ( FileOut )
121
122## This is the end
[3671]123sys.exit (0)
[3620]124   
125### ===========================================================================
126###
127###                               That's all folk's !!!
128###
129### ===========================================================================
130
Note: See TracBrowser for help on using the repository browser.