1

is there a way to parse an entire ElementTree from a file and return it as a string in python? I would like to read the entire file into a single string value, for example grabbing the entire output of dump(tree)? Any help or advice would be greatly appreciated!

xml

import xml.etree.ElementTree as ET

print "Enter a filename"
filename = input()
tree = ET.parse(filename)
string = tree.tostring() ##is there a way to do something like this?

test.xml

<data>

     <serial>

     <serial name = "serial">SN001</serial>

     </serial>

     <items>

    <item>Test1 = Failed</item>

    <item>Test2 = Passed</item>

    <item>Test3 = Passed</item>

      </items>

</data>

1 Answer 1

2

tostring is a module function, not a method.

string = ET.tostring(tree.getroot())
Sign up to request clarification or add additional context in comments.

3 Comments

I tried something like that earlier and got an error saying that ElementTree has no attribute named 'tag'
@wheatfairies - Yep, I did, too. I've updated my answer.
Excellent! That was exactly what I needed. Thank you Rob. I will accept your answer when it becomes available.

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.