-1

I need to change the value of the parameters P_ModelName and P_ModelYear in the below xml code to some value which is in variable Var_modelname and Var_modelyear through python function.

Var_modelname = OEM_2020 Var_modelyear = 2020

please help me how to change these two parameter values in XML using python function

XML code before edit:

<PARAMETER xsi:type="parameterEntry">
 <NAME xsi:type="unicode">P_ModelName</NAME>
 <VALUE format-rev="1" xsi:type="valueBaseExpression">
 <VALUE xsi:type="unicode">OEM_2019</VALUE>
 </VALUE>
</PARAMETER>

<PARAMETER xsi:type="parameterEntry">
 <NAME xsi:type="unicode">P_ModelYear</NAME>
 <VALUE format-rev="1" xsi:type="valueBaseExpression">
 <VALUE xsi:type="unicode">2019</VALUE>
 </VALUE>
</PARAMETER>

The python function should edit the xml code as below with P_ModelName = OEM_2020 and P_ModelYear=2020

XML code after edit:

<PARAMETER xsi:type="parameterEntry">
 <NAME xsi:type="unicode">P_ModelName</NAME>
 <VALUE format-rev="1" xsi:type="valueBaseExpression">
 <VALUE xsi:type="unicode">OEM_2020</VALUE>
 </VALUE>
</PARAMETER>

<PARAMETER xsi:type="parameterEntry">
 <NAME xsi:type="unicode">P_ModelYear</NAME>
 <VALUE format-rev="1" xsi:type="valueBaseExpression">
 <VALUE xsi:type="unicode">2020</VALUE>
 </VALUE>
</PARAMETER>
Kumar
  • 1
  • 1
  • see [ElementTree XML API](https://docs.python.org/3.7/library/xml.etree.elementtree.html) – napuzba Sep 16 '19 at 10:40
  • 1
    Welcome to SO. You state that you "have errors" but forgot to post the code generating those errors, as well as the exact error message and full traceback. Please edit your question to include a proper [mcve] – bruno desthuilliers Sep 16 '19 at 10:53
  • Kumar, in the edit you just removed "I end up with errors". That did not improve the question. Show us what you tried and where you are stuck. And your "XML code" is not XML since there is no root element. – mzjn Sep 17 '19 at 10:17

1 Answers1

0

def fun(old, new, xmlpath):
    with open(xmlpath, 'r+') as f:
        xmlcode = f.read()
        f.write(xmlcode.replace(old, new)

fun('2019', '2020', 'blah.xml')
Evan Brittain
  • 547
  • 5
  • 15
  • The provided answer was flagged for review as a Low Quality Post. Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). This provided answer may be correct, but it could benefit from an explanation. Code only answers are not considered "good" answers. From [review](https://stackoverflow.com/review/low-quality-posts/24068079). – Trenton McKinney Sep 17 '19 at 06:26
  • @Evan Brittain, My expectation is not to find and replace the value in the xml , I need to change the Value to 2020 by passing the value from the variable Var_modelyear , Note : I dont be knowing the old value to do find and replace . I need to simply change the value of P_Modelyear in the xml. Please support, Thanks in Advance . – Kumar Sep 17 '19 at 09:18