
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to get specific nodes in xml file in Python?
Using the xml library you can get any node you want from the xml file. But for extracting a given node, you'd need to know how to use xpath to get it. You can learn more about XPath here:https://www.w3schools.com/xml/xml_xpath.asp.
Example
For example, assume you have a xml file with following structure,
<bookstore> <book category="cooking"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="children"> <title lang="en">Harry Potter</title> <author>J K. Rowling</author> <year>2005</year> <price>29.99</price> </book> </bookstore>
And you want to extract all title nodes with lang attribute en, then you'd have the code −
from xml.etree.ElementTree import ElementTree tree = ElementTree() root = tree.parse("my_file.xml") for node in root.findall("//title[@lang='en']"): for type in node.getchildren(): print(type.text)
- Related Articles
- How to delete the specific node from the XML file using PowerShell?
- How to update the specific node of the XML file using PowerShell?
- How to iterate over nodes of XML in JSP?
- How to echo XML file in PHP
- How to read the XML file in PowerShell?
- How to create Python objects based on an XML file?
- How to exclude specific file names using Get-ChildItem in PowerShell?
- How to convert XML file into array in PHP?
- Export Preferences to XML file in Java
- How to retrieve specific file(s) information using Get-ChildItem in PowerShell?
- How to Delete Specific Line from a Text File in Python?
- How to get the file name from the file path in Python?
- How to create animation using XML file in an Android App?
- Extract csv file specific columns to list in Python
- Transforming XML file into fixed length flat file in SAP

Advertisements