python xml etree elementtree findall example
Sep 24, 2025 am 02:25 AMUse findall() to find all matching elements in XML. 1. Get all book elements through root.findall('book') and iterate; 2. Use book.find('title').text to extract child element text; 3. Use book.get('id') to obtain attribute values; 4. Support simple XPaths such as 'book[@id]' or './/title' to find attributes or deep nested elements; 5. Conditional filtering needs to be implemented manually (such as price > 40). This method returns a list of matching elements, combining find() and findtext() can efficiently extract structured data.
Using the xml.etree.ElementTree
module to parse XML in Python is a common requirement. findall()
method is used to find all matching child elements under the current node (supports label names or XPath paths). The following is a simple but complete example to demonstrate how to use findall()
.

? Basic usage: findall()
finds multiple elements
Suppose we have the following XML file (save as books.xml
):
<library> <book id="1"> <title>Python Crash Course</title> <author>Eric Matthes</author> <price>29.99</price> </book> <book id="2"> <title>Fluent Python</title> <author>Luciano Ramalho</author> <price>45.00</price> </book> <book id="3"> <title>Learning XML</title> <author>Erik T. Ray</author> <price>39.95</price> </book> </library>
? Sample code: Read and find all titles and authors
import xml.etree.ElementTree as ET # Load XML file tree = ET.parse('books.xml') root = tree.getroot() # Use findall() to find all book elements books = root.findall('book') # traverse each book element and extract information for book in books: title = book.find('title').text # find() Get the first matching child element author = book.find('author').text price = book.find('price').text book_id = book.get('id') # Get the attribute print(f"ID: {book_id}, Title: {title}, Author: {author}, Price: ${price}")
Output result:

ID: 1, Title: Python Crash Course, Author: Eric Matthes, Price: $29.99 ID: 2, Title: Fluent Python, Author: Luciano Ramalho, Price: $45.00 ID: 3, Title: Learning XML, Author: Erik T. Ray, Price: $39.95
? findall() supports XPath subsets (common techniques)
You can use a simple XPath expression in findall()
:
# Find all prices > 40 books (Note: ElementTree does not support conditional filtering syntax, it needs to be judged manually) for book in root.findall('book'): price = float(book.find('price').text) if price > 40: print(book.find('title').text, f"(${price})") # Output: # Fluent Python ($45.0)
?? Note:
ElementTree
'sfindall()
only supports limited XPath syntax, such as:
tag
: direct child elementtag/subtag
./tag
*
Wildcard- Basic paths such as
[@attribute]
For example:
# Find all books with id attributes books_with_id = root.findall('book[@id]') # Find all title elements (no matter how deep the nesting is, './/title' is available) all_titles = root.findall('.//title') # Similar to //title in XPath
? Summary: Comparison of common methods
method | illustrate |
---|---|
find(match) | Returns the first matching child element, None is found |
findall(match) | Returns a list of all matching child elements (even if empty) |
findtext(match) | Directly return the text content of the matching element |
Example:
first_book = root.find('book') # first book titles = root.findall('book/title') # All title elements all_authors = [a.text for a in root.findall('book/author')]
Basically that's it. findall()
is one of the most commonly used tools for processing batch XML data. It can easily extract structured information with find()
and attribute access.
The above is the detailed content of python xml etree elementtree findall example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Python is a simple and powerful testing tool in Python. After installation, test files are automatically discovered according to naming rules. Write a function starting with test_ for assertion testing, use @pytest.fixture to create reusable test data, verify exceptions through pytest.raises, supports running specified tests and multiple command line options, and improves testing efficiency.

Table of Contents What is Bitcoin Improvement Proposal (BIP)? Why is BIP so important? How does the historical BIP process work for Bitcoin Improvement Proposal (BIP)? What is a BIP type signal and how does a miner send it? Taproot and Cons of Quick Trial of BIP Conclusion?Any improvements to Bitcoin have been made since 2011 through a system called Bitcoin Improvement Proposal or “BIP.” Bitcoin Improvement Proposal (BIP) provides guidelines for how Bitcoin can develop in general, there are three possible types of BIP, two of which are related to the technological changes in Bitcoin each BIP starts with informal discussions among Bitcoin developers who can gather anywhere, including Twi

Theargparsemoduleistherecommendedwaytohandlecommand-lineargumentsinPython,providingrobustparsing,typevalidation,helpmessages,anderrorhandling;usesys.argvforsimplecasesrequiringminimalsetup.

Import@contextmanagerfromcontextlibanddefineageneratorfunctionthatyieldsexactlyonce,wherecodebeforeyieldactsasenterandcodeafteryield(preferablyinfinally)actsas__exit__.2.Usethefunctioninawithstatement,wheretheyieldedvalueisaccessibleviaas,andthesetup

Identifyrepetitivetasksworthautomating,suchasorganizingfilesorsendingemails,focusingonthosethatoccurfrequentlyandtakesignificanttime.2.UseappropriatePythonlibrarieslikeos,shutil,glob,smtplib,requests,BeautifulSoup,andseleniumforfileoperations,email,w

Python comes with its own HTTP server, which can quickly build local services. Use the python-mhttp.server8000 command to start the file sharing service on the specified port, and the browser visits http://localhost:8000 to view the directory contents; if you need a custom response, you can write processing logic through BaseHTTPRequestHandler, and implement a simple web service after running the script. It is suitable for testing and development, but is not recommended for production environments.

AsynchronousfunctionsinPythonaredefinedusingasyncdef,allowingnon-blockingexecutionofI/O-boundtasksviaawaitinsidecoroutines;theasyncio.run()functionstartstheeventlooptorunthesecoroutines,enablingconcurrenttaskexecutionwithasyncio.create_task()andeffic

ToreadenvironmentvariablesinPython,useos.environ.get()method.Importosmodule,accessvariablesviaos.environ['VAR_NAME']orsafelywithos.environ.get('VAR_NAME','default')toavoidKeyError,recommendedforproductionuse.
