Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

Python xml elem.text.replace(original, today) works inconsitenly

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:

  1. 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'>
  1. 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:

  1. 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?

  2. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First thing: you can not replace a string ('#DATE#') by a datetime object (your datetime.date.today() here).

You have to format this date object into a string, and that's actually the job of the .strftime('format') method you use inside your kwt function.

What means you could do this for example (I simplified your code a little):

data = ["#DATE#T07:05:07Z", "#DATE#T07:06:00+01:00"]

today = datetime.date.today().strftime('%Y-%m-%d')

for text in data:
    if "#DATE#" in text:
        text_init = text
        text = text.replace("#DATE#", today)
        print(text_init, " => ", text)

This should answer to your question 1.b

Questions 1.a and 1.b

You're processing every element that contains the string '#DATE#', which is the case for your two strings ("#DATE#" and "#DATE#T07:06:00+01:00"). There is nothing wrong here, since I suppose one of the elements in your xml file contains only the string "#DATE#"?

Question 2.b

I don't get it? In your second case, the first string was "#Date#", so it's pretty normal the full string is replaced, don't you think?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...