Concepts / Handling XML Parsing Errors

Handling XML Parsing Errors

fromstring converts an XML string into a tree structure, enabling programmatic access to its data.

  • Programming
Interactive lab

Try it: XML Element Trees

How ET.fromstring() turns XML text into a tree of Elements (tag, attributes, .text), and how find(), findall() and iter() walk that tree along a path such as users/user.

How it works

  1. The parser reads start tags, text and end tags left to right, keeping a stack of open elements; each start tag becomes an Element that is a child of the element on top of the stack.
  2. Text before an element's first child becomes its .text (whitespace included); an end tag must match the open element or parsing stops with ParseError.
  3. findall(path) starts at the element it is called on (the root is not part of the path) and follows each path segment down one level of children.
  4. find(path) returns the first match or None; iter(tag) visits every element in document order, including the root.
  5. Reading .text, .tag or .get('attr') on each result gives the extracted values; reading an attribute from None raises AttributeError.

Default run (29 steps): ET.fromstring() receives 183 characters. The parser reads tags left to right and keeps a stack of open elements. … findall() returned a list of 2 elements; reading e.get('x') from each gives ['2', '7'].

Simplified: A small, hand-written XML parser for a subset: elements, attributes, text, self-closing tags, comments, CDATA, processing instructions and the five predefined entities plus numeric character references. DOCTYPE/DTDs and namespaces are not supported. Error messages follow Python's expat parser for these cases (column numbers can differ for non-ASCII documents). Paths support tags, *, ., //, [@attr], [@attr='v'], [tag] and [n].

Educational simulation

Loading the simulation…

From Text to Navigable Data

An XML document may begin as a plain string: a sequence of characters containing opening tags, closing tags, text, and attributes. That string is not yet a structure your program can conveniently navigate. The fromstring function reads the XML string and builds a hierarchical tree that mirrors the nesting of the XML elements.

XML string<person>...</person>personroot Elementnameelementphoneelementfromstringcontainscontains
How does a flat XML string become a nested tree that a program can access?

The Root Element After Parsing

Worked example

Inspecting a Parsed Person Document

A program receives the XML string <person><name>Ada</name><phone>555-0100</phone></person>. What does fromstring provide?

  1. 1
    Parse the string

    Applying fromstring to the XML string creates an Element object representing the root element.

  2. 2
    Identify the entry point

    The root Element is person, so its tag property is person. This Element is the entry point to the entire tree.

  3. 3
    Use the tree

    From the person element, the program can search for nested elements such as name and phone.

Result

fromstring changes the XML from plain text into a tree whose root Element is person.

Key point

The result of fromstring is an Element object, not merely another string. Its tag identifies the element's name, and the root Element provides access to the rest of the parsed tree.

When Parsing Cannot Build a Tree

The useful result of fromstring is a tree. If the supplied XML is invalid or malformed, that successful tree-building step cannot be completed. This is the first point to investigate when XML processing fails: determine whether the input is valid enough for fromstring to produce a root Element before attempting to search it.

Valid XMLnested tags are usableElement treeroot Element availableInvalid XMLcannot form the intendedtreeParsing problemno usable root Elementfromstringfromstring
What differs when fromstring receives well-formed XML instead of invalid XML?

Finding and Reading Element Data

Once fromstring has produced a tree, use find with a tag name to locate the first element with that matching tag name. The returned value is an Element object when the tag exists. You can then read the element's content through .text or retrieve one of its attributes with .get().

personroot ElementnameAdanamefirst matching Elementphone555-0100containscontainsfind name
How does find locate a requested tag within the parsed XML tree?
XML data locationPython accessWhat it provides
Between an element's opening and closing tags.textThe element's text content
As a key-value pair in the opening tag.get()The value of a named attribute

Text content and attributes are separate kinds of XML data.

Worked example

Extracting Text and an Attribute

Consider the XML element <person status="active"><name>Ada</name></person>. How would the tree's data be interpreted?

  1. 1
    Locate name

    find with the tag name name returns the name Element.

  2. 2
    Read text

    The name Element's .text value is Ada because Ada appears between the opening and closing name tags.

  3. 3
    Read the attribute

    The person Element's .get() method can retrieve the value active for the status attribute.

  4. 4
    Keep the locations distinct

    Ada is element text, while active is an attribute value. The two values come from different parts of the XML.

Result

Use .text for content between tags and .get() for a named attribute in an opening tag.

Missing Elements and Safe Checks

  • Common mistake

    Assuming every find call returns an Element

    What it looks like

    Searching for a tag that is not present and immediately reading its .text property

    Why it fails

    find returns None when the requested tag does not exist. None does not provide the Element properties you intended to read.

    Do this instead

    Check whether find returned a valid element before accessing .text or calling .get().

  • Common mistake

    Using .text to retrieve an attribute

    What it looks like

    Trying to read the status value from an opening tag as though it were element content

    Why it fails

    Attributes and text content are stored in different places in XML.

    Do this instead

    Use .text for content between tags and .get() for a named attribute.

  • Common mistake

    Treating whitespace as part of the meaningful value

    What it looks like

    Reading text that includes indentation, newlines, or spaces from the original XML

    Why it fails

    The .text property can include whitespace present in the source XML.

    Do this instead

    Use .strip() when the extracted text should have surrounding whitespace removed.

  • Common mistake

    Searching before confirming that parsing produced a tree

    What it looks like

    Trying to use find after fromstring was given invalid XML

    Why it fails

    The navigation methods depend on a successfully created Element tree.

    Do this instead

    Handle the parsing problem first, then search the tree only when a usable root Element is available.

Best practice

Treat XML extraction as a guarded sequence: parse the string, confirm that a tree is available, use find, check the returned Element, and only then access .text or .get(). This prevents a missing tag from turning into an attempt to read properties from None.

Practice the Extraction Sequence

MEDIUM

A document contains a root element named person, a nested element named phone, and a status attribute on person. Describe the sequence you would use to parse the XML, locate phone, obtain its text, and retrieve status. Then explain what you would check before reading phone's properties.

Hints
  • Begin with fromstring because the input starts as a plain XML string.
  • Use find with the tag name phone.
  • Use .text for the phone content and .get() for the status attribute.
  • find may return None, so check the result before reading its properties.

What do you think happens?

If find searches for a tag that does not exist, what should you expect before trying to read .text?

  • A matching Element containing empty text

  • None, which must be checked

  • The root Element again

Reveal answer
Answer:

None, which must be checked

The find method returns None when the requested tag does not exist. Accessing .text or .get() without checking can cause an error.

The Reliable Workflow

  1. 1
    Start with the XML string and pass it to fromstring to build a hierarchical tree.
  2. 2
    Use the returned root Element as the entry point to the tree.
  3. 3
    Call find with a tag name to locate the first matching element.
  4. 4
    Check that find returned a valid Element rather than None.
  5. 5
    Read element content with .text, cleaning surrounding whitespace with .strip() when needed.
  6. 6
    Read attribute values with .get(), remembering that attributes and text are separate.

The central idea is to move carefully from representation to navigation to extraction. fromstring turns plain XML text into an Element tree. find locates an element in that tree. .text reads content between tags, while .get() reads an attribute value. Checking each stage makes missing or malformed data easier to handle.

Key Takeaways

  • fromstring converts an XML string into a hierarchical tree and returns an Element representing the root.
  • find locates the first element with a matching tag name.
  • The .text property reads content between an element's opening and closing tags.
  • The .get() method retrieves a named attribute value.
  • Always check both the parsing stage and the result of find before accessing element properties.

More concepts starting with H