I'm trying to overwrite two date tag.text in an xml, with the "xml.etree.Elementree as ET". (Our companies user account control does not allow lxml, for some reason.)
Expected result:
date1: #DATE#T07:05:07Z ==> 2021-01-07T07:05:07Z
date2: #DATE#T07:06:00+01:00 ==> 2021-01-07T07:06:00+01:00
Here is my code:
def kwt():
now = datetime.datetime.now()
today = datetime.date.today().day
kwt_dt = now + datetime.timedelta(days=int(today), hours=1)
date = kwt_dt.strftime('%Y-%m-%dT%H:%M:%S+01:00')
return date
today = kwt()
with open(path_for_slup, "r+") as slup:
slup_tree = ET.parse(path_for_slup)
slup_root = slup_tree.getroot()
for elem in slup_root.iter():
if str(elem.text).__contains__("#DATE#"):
try:
old_elememt_text = elem.text
print("Old elem.text:", elem.text)
elem.text = elem.text.replace("#DATE#", today)
print("New elem.text:", elem.text)
new_elememt_text = elem.text
except:
print("There is a problem with overwriting the #DATE#")
print("Old elem.text:", type(elem.text))
Actual result:
- case with the use of today = datetime.date.today()
Old elem.text: #DATE#
There is a problem with overwriting the #DATE#
Old elem.text: <class 'str'>
Old elem.text: #DATE#T07:06:00+01:00
There is a problem with overwriting the #DATE#
Old elem.text: <class 'str'>
- case: with the use of the kwt() function
Old elem.text: #DATE#
New elem.text: 2021-01-14T
Old elem.text: #DATE#T07:06:00+01:00
New elem.text: 2021-01-14TT07:06:00+01:00
Process finished with exit code 0
There are several things I do not get:
case:
a. I use the same code for both #DATE# exchanges, but the first time it recognises that "old elem.text" should be just #DATE# and the second time it does not. Why?
b. What kind of problem could elem.text.replace() have that it can't replace the #DATE# with the var today?
case:
a. same as 1.case a.
b. At the first #DATE# the whole tag text was replaced, at the second only the #DATE# part was replaced. Again, why?
Example XML
<SOAP-ENV:Body>
<slupClient:SLUP>
<tagname1>1</tagname1>
<tagname2>XXX</tagname2>
<tagname3>#DATE#T07:05:07Z</tagname3> <!-- T07:05:07Z -->
.
.
.
<tagname20>
<tagname>ABC</tagname>
<val>#DATE#T07:06:00+01:00</val> <!--T07:06:00+01:00-->
</tagname20>
Any help would appreciated.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…