1

Code

When running the following code I cannot save the output as an xml file as I get the following error AttributeError: 'ElementTree' object has no attribute 'tag'(in traceback). There is a similarly named question on SO but I do not believe it is relevant to mine as it was to do with parsing from the root node, not saving.

Code

import xml.etree.ElementTree as ET
print('\n'*5)

xmlfile = 'widget.XML'

tree = ET.parse(xmlfile)
root = tree.getroot()

#ET.dump(tree)# prints the xml file to console,shows xml indentation
print('\n'*2)
for elm in root.findall("./Common/ForceBinary"):
    print(elm.attrib)
    elm.attrib = {'type': 'integer', 'value': '0'}

with open("new_file.xml", "w") as f:
    f.write(ET.tostring(tree))

Traceback

{'type': 'integer', 'value': '1'}
Traceback (most recent call last):
  File "/Users/user/Desktop/MY_PY/x_08.py", line 16, in <module>
    f.write(ET.tostring(tree))
  File "/Users/user/opt/anaconda3/lib/python3.7/xml/etree/ElementTree.py", line 1136, in tostring
    short_empty_elements=short_empty_elements)
  File "/Users/user/opt/anaconda3/lib/python3.7/xml/etree/ElementTree.py", line 777, in write
    short_empty_elements=short_empty_elements)
  File "/Users/user/opt/anaconda3/lib/python3.7/xml/etree/ElementTree.py", line 901, in _serialize_xml
    tag = elem.tag
AttributeError: 'ElementTree' object has no attribute 'tag'

2 Answers 2

3

ElementTree.tostring() operates on an Element, which is not the same as ElementTree. You've already extracted the root node via tree.getroot() - you just need ET.tostring(root) instead.

The reason the API is this way is because Element is intended as the data structure for an in-memory parsed XML object, while ElementTree is mostly just a serialization-deserialization helper (perhaps the Tree naming was not the best idea) to bridge those Elements with the outside world.

A related question about the difference between the two: What is the difference between a ElementTree and an Element? (python xml)

Sign up to request clarification or add additional context in comments.

3 Comments

How do you then write the xml to a file?
As you would any other string and as you tried in your question, open a file and f.write() to it. You've asked for an explanation why the original solution didn't work and here it is - however if writing XML to a file is all you need, the tree.write() shortcut is the way to go.
Thank you Mike, much appreciated.
2

After trying quite a few methods to write the output to an xml file this is the line that worked (I don't know why, if anyone has an explanation I would be happy to accept it as the answer).

tree.write("sdn_edit2.xml")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.