Using python import lxml I am able to print a list of the path for every element recursively:
from lxml import etree
root = etree.parse(xml_file)
for e in root.iter():
path = root.getelementpath(e)
print(path)
Results:
TreatmentEpisodes
TreatmentEpisodes/TreatmentEpisode
TreatmentEpisodes/TreatmentEpisode/SourceRecordIdentifier
TreatmentEpisodes/TreatmentEpisode/FederalTaxIdentifier
TreatmentEpisodes/TreatmentEpisode/ClientSourceRecordIdentifier
etc.
Note: I am working with this XSD: https://www.myflfamilies.com/service-programs/samh/155-2/155-2-v14/schemas/TreatmentEpisodeDataset.xsd
I want to do the same thing using import xml.etree.ElementTree as ET ...but ElementTree does not seem to have an equivalent function to lxml getelementpath().
I've read the docs. I've googled for days. I've experimented with XPath. I've guessed using iter() and tried "getpath()", "Element.getpath()", etc. hoping to discover an undocumented feature. Fail.
Perhaps I am experiencing an extreme case of "user error" and please forgive me if this is a duplicate.
I thought I found the answer here: Get Xpath dynamically using ElementTree getpath() but the XPathEvaluator only seems to operate on a 'known' element - it doesn't have an option for "give me everything".
Here is what I tried:
import xml.etree.ElementTree as ET
tree = etree.parse(xml_file)
for entry in tree.xpath('//TreatmentEpisode'):
print(entry)
Results:
<Element TreatmentEpisode at 0xffff8f8c8a00>
What I was hoping for:
TreatmentEpisodes/TreatmentEpisode
...however, even if I received what I hoped for, I am still not sure how to obtain the full path for every element. As I understand the XPath docs, they only operate on 'known' element names. i.e. tree.xpath() seems to require the element name to be known beforehand.