Skip to content

Instantly share code, notes, and snippets.

@alorence
Created August 30, 2018 12:59
Show Gist options
  • Save alorence/8420b788678089ef35be5f7f413e4628 to your computer and use it in GitHub Desktop.
Save alorence/8420b788678089ef35be5f7f413e4628 to your computer and use it in GitHub Desktop.
An example of namespace management and simple Xpath search with ElementTree
# -*- coding: utf-8 -*-
from __future__ import print_function
import xml.etree.ElementTree as ET
xdoc = """
<ns:response xmlns:ns="http://myserver.example.com">
<ns:return>
<example>
<inner>Some text here</inner>
</example>
</ns:return>
</ns:response>
"""
ns = {"ns": "http://myserver.example.com"}
root = ET.fromstring(xdoc)
for index, child in enumerate(root):
print("child", index, ":", child)
print("-------------------------")
print("ns:return:", root.find("ns:return", ns))
print("ALL inner tags:", root.findall("inner", ns))
print("xpath search:", root.find(".//example/inner"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment