pythonxmlcelementtree

Object has no attribute 'text' when parsing xml


I'm using ElementTree to parse a simple string of xml:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">maison</string>

That's the root. All I want is the contents of that tag, to convert into json. 'translation' is the xml text.

tree = ET.ElementTree(translation)
        root = tree.getroot()

        return root.text

It looks simple enough but it's throwing the " Object has no attribute 'text' " error. What am I doing wrong?


Solution

  • You should use fromstring to parse that xml, to get the text for this tag, do this:

    tree = ET.fromstring(translate)
    print tree.text()
    
    'maison'
    

    should also point out that ET.ElementTree doesn't have attribute text, you can read more information on this link