1

xml code is this

<foo>
<bar key="value">text</bar>
</foo>

Python code is:

import xml.etree.ElementTree as ET
xml=ET.fromstring(contents)
xml.find('./bar').attrib['key']

Output: 'value'

What must be placed in contents place of the above python code to get the value as output?

If i write as contents only it is giving an error as contents not defined.

1
  • If i write whole big xml file in contents , still it pops that there is a syntax error in that line. Commented May 31, 2017 at 8:16

1 Answer 1

2

It works if the XML is provided as a triple-quoted string. This allows you to include unescaped quotes within the string.

import xml.etree.ElementTree as ET

contents = """
<foo>
<bar key="value">text</bar>
</foo>"""

xml = ET.fromstring(contents)
print xml.find('./bar').attrib['key']
Sign up to request clarification or add additional context in comments.

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.