59.2k views
3 votes
What is the method to cause Python to parse XML that is stored in a string?

User Jkmacc
by
7.6k points

1 Answer

1 vote

Final answer:

To parse XML stored in a string in Python, you can use the xml.etree.ElementTree module. Create an ElementTree object from the string and access the XML elements using methods and attributes.

Step-by-step explanation:

In Python, you can use the xml.etree.ElementTree module to parse XML stored in a string. You can do this by creating an ElementTree object from the string and then accessing the XML elements using the object's methods and attributes.

Here's an example:

import xml.etree.ElementTree as ET

xml_string = "<root><item>Apple</item><item>Banana</item></root>"

tree = ET.ElementTree(ET.fromstring(xml_string))

root = tree.getroot()

for item in root:
print(item.text)

This code creates an ElementTree object from the XML string, and then uses the getroot() method to access the root element. You can then iterate over the child elements using a for loop, and access the text content of each element using the text attribute.

User Redreinard
by
8.3k points
Welcome to QAmmunity.org, where you can ask questions and receive answers from other members of our community.