0

I have the following python code:

from xml.etree import ElementTree as et
from optparse import OptionParser
import ConfigParser
import fileinput, sys
import os


config_file = 'ClientConfig.xml'
tree = et.parse(config_file)
root = tree.getroot()

for element in root.findall("/client/config/TEST_CLIENT"):
    for elem in element.iter(tag='Item'):
        print elem.tag, elem.attrib

Is there a way for me to print the xpath directly for each element as opposed to rebuilding it using the elem.tag and elem.attrib options? That is, I want to be able to print each elements full xpath

Zee
  • 1,321
  • 2
  • 18
  • 41

1 Answers1

0

You would need to use lxml.etree and getpath() method for it:

for element in root.findall("/client/config/TEST_CLIENT"):
    for elem in element.iter(tag='Item'):
        print(tree.getpath(elem))
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • This ended up being the solution. I was avoiding lxml but its far superior to ElementTree – Zee Jul 28 '16 at 20:22