Repository navigation
Expand file tree
/
Copy pathXMLengine.py
More file actions
1906 lines (1524 loc) · 64.4 KB
/
Copy pathXMLengine.py
File metadata and controls
1906 lines (1524 loc) · 64.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# This file is part of code_saturne, a general-purpose CFD tool.
#
# Copyright (C) 1998-2022 EDF S.A.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# Street, Fifth Floor, Boston, MA 02110-1301, USA.
#-------------------------------------------------------------------------------
"""
This module defines a Lightweight XML constructor and reader.
It provides a management of the XML document, which reflets the treated case.
This module defines the following classes:
- Dico
- XMLElement
- XMLDocument
- Case
- XMLDocumentTestCase
"""
#-------------------------------------------------------------------------------
# Library modules import
#-------------------------------------------------------------------------------
import os, sys, unittest, logging
from xml.dom.minidom import Document, parse, parseString, Node
#-------------------------------------------------------------------------------
# log config
#-------------------------------------------------------------------------------
logging.basicConfig()
log = logging.getLogger("XMLengine")
#-------------------------------------------------------------------------------
# Checker of XML file syntax
#-------------------------------------------------------------------------------
def xmlChecker(filename):
"""Try to open the xml file, and return a message if an error occurs.
@param filename name of the file of parameters ith its absolute path
@return m error message
"""
from xml.sax.handler import ContentHandler
from xml.sax import make_parser
m = ""
try:
p = make_parser()
p.setContentHandler(ContentHandler())
p.parse(filename)
except Exception as e:
f = os.path.basename(filename)
m = "%s file reading error. \n\n"\
"This file is not in accordance with XML specifications.\n\n"\
"The parsing syntax error is:\n\n%s" % (f, e)
return m
#-------------------------------------------------------------------------------
# Simple class wich emulate a basic dictionary, but allows to make
# everytimes verification on values and keys
#-------------------------------------------------------------------------------
class Dico:
"""
This define a simple class in order to store informations about the case.
These informations are useful only for the current session, and are
forgotten for the next one.
"""
def __init__(self):
"""
Create a dictionary and the associated key.
"""
self.data = {}
self.data['saved'] = "yes"
self.data['run_type'] = 'standard'
self.data['oturns'] = False
self.data['xmlfile'] = ""
self.data['pythonfile'] = ""
self.data['mesh_path'] = ""
self.data['user_src_path'] = ""
self.data['data_path'] = ""
self.data['resu_path'] = ""
self.data['relevant_subdir'] = "no"
self.data['case_path'] = ""
self.data['job_model'] = None
self.data['salome'] = False
self.data['module'] = None
self.data['package'] = None
self.data['current_page'] = ""
self.data['current_index'] = None
self.data['current_tab'] = -1
self.data['undo'] = []
self.data['redo'] = []
self.data['probes'] = None
self.data['dump_python'] = []
self.data['python_redo'] = []
def _errorExit(self, msg):
"""
"""
print('CASE DICO ERROR')
raise ValueError(msg)
def __setitem__(self, key, name):
"""
Store values in the data dictionary when the key exists
in the dictionary.
"""
if hasattr(self, 'data'):
if key in self.data:
self.data[key] = name
else:
msg = "There is an error in the use of the dictionary "+ \
"with the key named: " + key + ". \n" + \
"The application will finish.\n" \
"Please contact the development team."
print(self._errorExit(msg))
def __getitem__(self, key):
"""
Extraction of informations from the data dictionary.
"""
if hasattr(self, 'data'):
if key in self.data:
return self.data[key]
else:
return None
def __printDict(self):
"""
Simple tool wich prints the dictionary contents on the current terminal.
"""
if hasattr(self, 'data'):
for i in list(self.data.keys()):
print("%s -> %s" % (i, self.data[i]))
#-------------------------------------------------------------------------------
# Lightweight XML constructor and reader
#-------------------------------------------------------------------------------
class XMLElement:
"""
XML element base class
"""
def __init__(self, doc, el, case):
"""
Constructor.
"""
self.doc = doc
self.el = el
self.ca = case
def __errorExit(self, msg):
"""
"""
raise ValueError("XML ERROR:\n" + msg)
def toString(self):
"""
Print the XMLElement node to a simple string (without \n and \t).
Unicode characters are encoded.
"""
# self.el.toxml() would be enough, except for the root node,
# where the encoding type is written only where specified.
return self.el.toxml("utf-8").decode()
def toUnicodeString(self):
"""
Print the XMLElement node to an unicode string (without \n and \t).
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: do not use this method for comparison purposes!
"""
try:
# self.el.toxml() would be enough, except for the root node,
# where the encoding type is written only where specified.
return self.el.toxml("utf-8").decode()
except:
unicode_obj = self.toxml(encoding=sys.stdout.encoding)
return unicode_obj.decode()
def __str__(self):
"""
Print the XMLElement node with \n and \t.
Unicode string are decoded if it's possible by the standard output,
if not unicode characters are replaced by '?' character.
Warning: do not use this method for comparison purpose!
"""
try:
# self.el.toprettyxml() would be enough, except for the root,
# where the encoding type is written only where specified.
return self.el.toprettyxml(encoding="utf-8", indent=' ').decode()
except:
unicode_obj = self.el.toprettyxml(encoding=sys.stdout.encoding, indent=' ')
return unicode_obj.decode()
def __xmlLog(self):
"""Convenient method for log"""
if self.el.hasChildNodes() and len(self.el.childNodes) > 1:
return "\n" + self.__str__()
else:
return self.toUnicodeString()
def _inst(self, el):
"""
Transform a Element node to an instance of the XMLElement class.
"""
return XMLElement(self.doc, el, self.ca)
def xmlCreateAttribute(self, **kwargs):
"""
Set attributes to a XMLElement node, only if these attributes
do not already exist.
"""
for attr, value in list(kwargs.items()):
if not self.el.hasAttribute(attr):
self.el.setAttribute(attr, str(value))
log.debug("xmlCreateAttribute-> %s" % self.__xmlLog())
def xmlGetAttributeDictionary(self):
"""
Return the dictionary of the XMLElement node attributes.
"""
d = {}
if self.el.nodeType == Node.ELEMENT_NODE:
if self.el.hasAttributes():
attrs = self.el._get_attributes()
a_names = list(attrs.keys())
a_names.sort()
for a_name in a_names:
d[a_name] = attrs[a_name].value
return d
def xmlGetAttribute(self, attr, default=None):
"""
Return the value of the XMLElement node attribute.
Crash if the searched attribute does not exist and no default is provided.
"""
if not self.el.hasAttribute(attr):
if default is None:
node = self.__str__()
msg = "ElementNode: \n\n" \
+ node + "\n\nis missing attribute: \n\n" \
+ attr + "\n\nThe application will finish."
self.__errorExit(msg)
return default
else:
a = self.el.getAttributeNode(attr)
return a.value
def xmlSetAttribute(self, **kwargs):
"""
Set several attribute (key=value) to a node
"""
for attr, value in list(kwargs.items()):
self.el.setAttribute(attr, str(value))
log.debug("xmlSetAttribute-> %s" % self.__xmlLog())
def xmlDelAttribute(self, attr):
"""
Delete the XMLElement node attribute
"""
if self.el.hasAttribute(attr):
self.el.removeAttribute(attr)
log.debug("xmlDelAttribute-> %s %s" % (attr, self.__xmlLog()))
def __getitem__(self, attr):
"""
Return the XMLElement attribute's value
with a dictionary syntax: node['attr']
Return None if the searched attribute does not exist.
"""
a = self.el.getAttributeNode(attr)
if a:
return a.value
return None
def __setitem__(self, attr, value):
"""
Set a XMLElement attribute an its value
with a dictionary syntax: node['attr'] = value
"""
self.el.setAttribute(attr, str(value))
log.debug("__setitem__-> %s" % self.__xmlLog())
def __delitem__(self, name):
"""
Delete a XMLElement attribute with a dictionary syntax: del node['attr']
"""
self.xmlDelAttribute(name)
#log.debug("__delitem__-> %s" % self.__xmlLog())
def xmlSortByTagName(self):
"""
Return a dictionary which keys are the name of the node.
"""
d = {}
for node in self.el.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
dd = self._inst(node).xmlGetAttributeDictionary()
key = node.tagName
for k in list(dd.keys()): key = key + (k+dd[k])
d[key] = self._inst(node)
elif node.nodeType == Node.TEXT_NODE:
try:
k = float(node.data)
except:
k = node.data
d[k] = self._inst(node)
return d
def __cmp__(self, other):
"""
Return 0 if two XMLElement are the same, return 1 otherwise.
"""
if not other:
return 1
if not isinstance(other, XMLElement):
return 1
if self.el.nodeType == Node.ELEMENT_NODE:
if self.el.tagName != other.el.tagName:
return 1
elif self.el.nodeType == Node.TEXT_NODE:
try:
a = float(self.el.data)
b = float(other.el.data)
except:
a = self.el.data
b = other.el.data
if a != b:
return 1
if self.xmlGetAttributeDictionary() != other.xmlGetAttributeDictionary():
return 1
d1 = self.xmlSortByTagName()
d2 = other.xmlSortByTagName()
l1 = list(d1.keys())
l2 = list(d2.keys())
l1.sort()
l2.sort()
if l1 != l2:
return 1
if self.el.childNodes and other.el.childNodes:
for key in list(d1.keys()):
if d1[key] != d2[key]:
return 1
return 0
def __eq__(self, other):
"""
Compare two XMLDocument nodes equivalence.
"""
if self.__cmp__(other) == 1:
return False
else:
return True
def __ne__(self, other):
"""
Compare two XMLDocument nodes equivalence.
"""
if self.__cmp__(other) == 1:
return True
else:
return False
def _nodeWithAttrList(self, node, *attrList, **kwargs):
"""
Return a list of Element (and not XMLElement)!
"""
nodeList = []
# Get the nodes list
#
nodeL = []
iok = 0
try:
for attr in attrList:
if node.hasAttribute(str(attr)):
iok = 1
else:
iok = 0
break
if iok: nodeList = [node]
except Exception:
pass
if attrList and kwargs:
nodeL = nodeList
nodeList = []
for n in nodeL:
iok = 0
for k, v in list(kwargs.items()):
if n.getAttribute(str(k)) == str(v):
iok = 1
else:
iok = 0
break
if iok: nodeList.append(n)
if not attrList and not kwargs:
nodeList = nodeL
if node.childNodes:
for c in node.childNodes:
nodeList += self._nodeWithAttrList(c, *attrList, **kwargs)
return nodeList
def _nodeList(self, tag, *attrList, **kwargs):
"""
Return a list of Element (and not XMLElement)!
"""
nodeList = []
# Get the nodes list
#
nodeL = self.el.getElementsByTagName(tag)
for node in nodeL:
iok = 0
for attr in attrList:
if node.hasAttribute(str(attr)):
iok = 1
else:
iok = 0
break
if iok: nodeList.append(node)
if attrList and kwargs:
nodeL = nodeList
nodeList = []
for node in nodeL:
iok = 0
for k, v in list(kwargs.items()):
if node.getAttribute(str(k)) == str(v):
iok = 1
else:
iok = 0
break
if iok: nodeList.append(node)
if not attrList and not kwargs:
nodeList = nodeL
return nodeList
def _childNodeList(self, tag, *attrList, **kwargs):
"""
Return a list of first child Element node from the explored XMLElement node.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
childNodeList = []
if self.el.hasChildNodes():
for node in self.el.childNodes:
if node.nodeType == Node.ELEMENT_NODE:
if node.nodeName == tag and node in nodeList:
childNodeList.append(node)
return childNodeList
def xmlAddChild(self, tag, *attrList, **kwargs):
"""
Add a new XMLElement node as a child of the current
XMLElement node (i.e. self), with attributes and value.
"""
el = self.doc.createElement(tag)
for k in attrList:
el.setAttribute(k, "")
for k, v in list(kwargs.items()):
el.setAttribute(k, str(v))
nn = None
for n in self.el.childNodes:
if n.nodeType == self.doc.ELEMENT_NODE:
if sorted([n.nodeName, tag]) != [n.nodeName, tag]:
nn = n
break
if tag == "variable" and n.nodeName == "variable":
name1 = n.getAttributeNode("name").value
name2 = el.getAttributeNode("name").value
if sorted([name1, name2]) != [name1, name2]:
nn = n
break
if tag == "property" and n.nodeName == "property":
name1 = n.getAttributeNode("name").value
name2 = el.getAttributeNode("name").value
if sorted([name1, name2]) != [name1, name2]:
nn = n
break
# For user arrays, force the order of arrays to be that of creation
# The problem arises because in the current model these arrays
# have the type "property"
for k, v in list(kwargs.items()):
if (k, v) == ('type', 'user'):
nn = None
log.debug("xmlAddChild-> %s %s" % (tag, self.__xmlLog()))
return self._inst(self.el.insertBefore(el, nn))
def xmlSetTextNode(self, newTextNode):
"""
Replace old text value of a TEXT_NODE by the new one.
If the elementNode 'node' has no TEXT_NODE as childNodes,
it will be created.
"""
if newTextNode == "" or newTextNode is None : return
if type(newTextNode) != str: newTextNode = str(newTextNode)
if self.el.hasChildNodes():
for n in self.el.childNodes:
if n.nodeType == Node.TEXT_NODE:
n.data = newTextNode
else:
self._inst(
self.el.appendChild(
self.doc.createTextNode(newTextNode)))
log.debug("xmlSetTextNode-> %s" % self.__xmlLog())
def xmlSetData(self, tag, textNode, default=None, *attrList, **kwargs):
"""
Set the textNode in an elementNode, which is a single node.
If the searched 'tag' doesn't exist, it is created
and textNode is added as a child TEXT_NODE nodeType.
Return a XMLElement list of the created Node.
"""
# First we convert textNode in string, if necessary.
# About the precision display read :
# "B. Floating Point Arithmetic: Issues and Limitations
# http://www.python.org/doc/current/tut/node14.html"
#
if type(textNode) == float: textNode = str("%.12g" % (textNode))
if type(default) == float: default = str("%.12g" % (default))
if textNode == default:
textNode = None
nodeList = self._childNodeList(tag, *attrList, **kwargs)
elementList = []
# Add a new ELEMENT_NODE and a new TEXT_NODE
# or replace an existing TEXT_NODE
#
if textNode != None and not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
child.xmlSetTextNode(textNode)
elementList.append(child)
elif nodeList:
for node in nodeList:
child = self._inst(node)
if textNode != None:
child.xmlSetTextNode(textNode)
elementList.append(child)
else:
child.xmlRemoveNode()
return elementList
def xmlGetTextNode(self, sep=" "):
"""
"""
rc = []
if self.el.hasChildNodes():
for node in self.el.childNodes:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return sep.join(rc)
else:
return None
def xmlGetStringList(self, tag, *attrList, **kwargs):
"""
Return a list of TEXT_NODE associed to the tagName elements
from the explored elementNode.
"""
stringList = []
nodeList = self._nodeList(tag, *attrList, **kwargs)
if nodeList:
for node in nodeList:
data = self._inst(node).xmlGetTextNode()
if data:
stringList.append(data)
return stringList
def xmlGetChildStringList(self, tag, *attrList, **kwargs):
"""
Return a list of TEXT_NODE associed to the tagName elements
from the explored elementNode.
"""
stringList = []
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if nodeList:
for node in nodeList:
data = self._inst(node).xmlGetTextNode()
if data:
stringList.append(data)
return stringList
def xmlGetIntList(self, tag, *attrList, **kwargs):
"""
Return a list of integer insteed of a list of one string.
"""
intList = []
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
for s in stringList:
try:
intList.append(int(s))
except:
pass
return intList
def xmlGetString(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return a string and not a list of one string.
"""
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
string = stringList[0]
else:
msg = "There is an error in with the use of the xmlGetString method. "\
"There is more than one occurence of the tagName: " + tag
self.__errorExit(msg)
else:
string = ""
return string
def xmlGetChildString(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return a string and not a list of one string.
"""
stringList = self.xmlGetChildStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
string = stringList[0]
else:
msg = "There is an error in with the use of the xmlGetChildString method. "\
"There is more than one occurence of the tagName: " + tag
self.__errorExit(msg)
else:
string = ""
return string
def xmlGetInt(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return an integer and not a list of one string.
"""
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
try:
integer = int(stringList[0])
except:
integer = None
else:
msg = "There is an error in with the use of the xmlGetInt method. "\
"There is more than one occurence of the tagName: " + tag
self.__errorExit(msg)
else:
integer = None
return integer
def xmlGetDouble(self, tag, *attrList, **kwargs):
"""
Just verify that the returned list contains only one string variable.
Return a float and not a list of one string.
"""
stringList = self.xmlGetStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
try:
double = float(stringList[0])
except:
double = None
else:
msg = "There is an error in with the use of the xmlGetDouble method. "\
"There is more than one occurence of the tagName: " + tag
self.__errorExit(msg)
else:
double = None
return double
def xmlGetChildDouble(self, tag, *attrList, **kwargs):
"""
Just verify that te returned list contains only one string variable.
Return a float and not a list of one string.
"""
stringList = self.xmlGetChildStringList(tag, *attrList, **kwargs)
if stringList:
if len(stringList) == 1:
try:
double = float(stringList[0])
except:
double = None
else:
msg = "There is an error in with the use of the xmlGetChildDouble method. "\
"There is more than one occurence of the tagName: " + tag
self.__errorExit(msg)
else:
double = None
return double
def xmlAddComment(self, data):
"""
Create a comment XMLElement node.
"""
elt = self._inst( self.el.appendChild(self.doc.createComment(data)) )
log.debug("xmlAddComment-> %s" % self.__xmlLog())
return elt
def xmlGetNodeWithAttrList(self, *attrList, **kwargs):
"""
Return a list of XMLElement nodes from the explored
XMLElement node (i.e. self).
"""
return list(map(self._inst, self._nodeWithAttrList(self.el, *attrList, **kwargs)))
def xmlGetNodeList(self, tag, *attrList, **kwargs):
"""
Return a list of XMLElement nodes from the explored
XMLElement node (i.e. self).
"""
return list(map(self._inst, self._nodeList(tag, *attrList, **kwargs)))
def xmlGetNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlGetNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self.__errorExit(msg)
elif len(nodeList) == 1:
return self._inst(nodeList[0])
else:
return None
def xmlGetNodeByIdx(self, tag, idx, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
The returned element is the idx'th instance of the XMLElement class,
or None if no such element is present.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if idx > -1 and len(nodeList) > idx:
return self._inst(nodeList[idx])
else:
return None
def xmlGetChildNodeList(self, tag, *attrList, **kwargs):
"""
Return a list of XMLElement nodes from the explored elementNode.
Each element of the returned list is an instance of the XMLElement
class.
"""
return list(map(self._inst, self._childNodeList(tag, *attrList, **kwargs)))
def xmlGetChildNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlGetChildNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self.__errorExit(msg)
elif len(nodeList) == 1:
return self._inst(nodeList[0])
else:
return None
def xmlGetParentName(self):
"""
Return the name of a node's parent
"""
return str(str(self.el.parentNode.nodeName))
def xmlInitNodeList(self, tag, *attrList, **kwargs):
"""
Each element of the returned list is an instance
of the XMLElement class.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, str(v))
nodeList.append(child)
else:
l = []
for node in nodeList: l.append(self._inst(node))
nodeList = l
return nodeList
def xmlInitChildNodeList(self, tag, *attrList, **kwargs):
"""
Each element of the returned list is an instance
of the XMLElement class.
"""
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, str(v))
nodeList.append(child)
else:
l = []
for node in nodeList: l.append(self._inst(node))
nodeList = l
return nodeList
def xmlInitNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement node from the explored elementNode.
If the tag does not exist, it will be created.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._nodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, str(v))
else:
if len(nodeList) > 1:
msg = "There is an error with the use of the xmlInitNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self.__errorExit(msg)
else:
child = self._inst(nodeList[0])
return child
def xmlInitChildNode(self, tag, *attrList, **kwargs):
"""
Return a single XMLElement child node from the explored elementNode.
If the tag does not exist, it will be created.
The returned element is an instance of the XMLElement class.
"""
nodeList = self._childNodeList(tag, *attrList, **kwargs)
if not nodeList:
child = self.xmlAddChild(tag, *attrList, **kwargs)
for k in attrList: child.el.setAttribute(k, "")
for k, v in list(kwargs.items()): child.el.setAttribute(k, str(v))
else:
if len(nodeList) > 1:
msg = "There is an error in with the use of the xmlInitChildNode method. "\
"There is more than one occurence of the tag: " + tag
for n in nodeList: msg += "\n" + self._inst(n).__str__()
self.__errorExit(msg)
else:
child = self._inst(nodeList[0])
return child
def xmlChildsCopy(self, oldNode, deep=1000):
"""
Copy all childsNode of oldNode to the node newNode.
'deep' is the childs and little-childs level of the copy.
"""
if oldNode.el.hasChildNodes():
for n in oldNode.el.childNodes:
self._inst(self.el.appendChild(n.cloneNode(deep)))
log.debug("xmlChildsCopy-> %s" % self.__xmlLog())
def xmlMergeNode(self, oldNode, deep=1000):
"""
Merge all children of oldNode into node, then delete oldNode.
"""
if oldNode.el.hasChildNodes():
for n in oldNode.el.childNodes:
duplicate = False
if self.el.hasChildNodes():
for nr in self.el.childNodes:
if n == nr:
duplicate = True
break
if not duplicate:
self._inst(self.el.appendChild(n.cloneNode(deep)))