Issue
So I have an XML which has a line:
<factor-apply>1.2</factor-apply>
And this line is in my XML twice.
I would like to change the text for both lines such that they both change to:
<factor-apply>0.5</factor-apply>
My code is as follows:
import xml.etree.ElementTree as ET
xml_tree = ET.parse(TestXML.xml)
root = xml_tree.getroot()
root.find(".//{*}factor-apply").text = "0.5"
ET.tostring(root)
Now this changes the first factor line in my XML but not the second.
I tried to do
root.findall(".//{*}factor-apply").text = "0.5"
but I get the error message
AttributeError Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_5072\1499665917.py in <module>
3 xml_tree = ET.parse(TestXML.xml)
4 root = xml_tree.getroot()
----> 5 root.findall(".//{*}factor-apply").text = "0.5"
6 ET.tostring(root)
AttributeError: 'list' object has no attribute 'text'
I'm wondering if I would have to make a loop in order to this as findall isn't working?? Any suggestions would be appreciated.
I would like to be able to do this for any variable. So I have a line which corresponds to date of birth. But that line is there 10 times so I would want to change all 10 lines for example
Solution
Try something like
for factor in root.findall(".//{*}factor"):
factor.text = "0.5"
and see if it works. If it does, you can probably replace factor
with any other element name.
Answered By - Jack Fleeting
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.