Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
# Python: namespace-aware parsing with ElementTree import xml.etree.ElementTree as ET xml_data = """<?xml version="1.0"?> <root xmlns="http://example.com/default" xmlns:dc="http://purl.org/dc/elements/1.1/"> <item id="1"> <dc:title>XML Namespaces</dc:title> <description>A guide to XML namespaces.</description> </item> </root>""" tree = ET.fromstring(xml_data) # Clark notation: {namespace-uri}localname ns = { 'ex': 'http://example.com/default', 'dc': 'http://purl.org/dc/elements/1.1/', } for item in tree.findall('ex:item', ns): # Attribute id is in null namespace — no prefix needed print('ID:', item.get('id')) title = item.find('dc:title', ns) desc = item.find('ex:description', ns) print('Title:', title.text if title is not None else 'N/A') print('Desc: ', desc.text if desc is not None else 'N/A') # Accessing the tag directly returns Clark notation first_item = tree.find('{http://example.com/default}item') print('Tag:', first_item.tag) # Output: {http://example.com/default}item
Result
Open