Created
August 30, 2018 12:59
-
-
Save alorence/8420b788678089ef35be5f7f413e4628 to your computer and use it in GitHub Desktop.
An example of namespace management and simple Xpath search with ElementTree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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