Home >Backend Development >Python Tutorial >How Can I Extract Attribute Values from XML Nodes Using Python's ElementTree?

How Can I Extract Attribute Values from XML Nodes Using Python's ElementTree?

DDD
DDDOriginal
2024-12-17 06:00:28227browse

How Can I Extract Attribute Values from XML Nodes Using Python's ElementTree?

Parsing XML to Retrieve Node Attribute Instances

In the provided XML structure:

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

The task is to extract the values of the "foobar" attribute for each "type" node.

Solution Using ElementTree

The ElementTree module offers a convenient way to parse XML and access node attributes. Here's how you can implement it:

import xml.etree.ElementTree as ET

# Parse the XML
root = ET.parse('input.xml').getroot()

# Iterate over the "type" nodes
for type_tag in root.findall('bar/type'):
    # Get the value of the "foobar" attribute
    value = type_tag.get('foobar')

    # Print the value
    print(value)

This code will print the values "1" and "2", as desired.

The above is the detailed content of How Can I Extract Attribute Values from XML Nodes Using Python's ElementTree?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn