Jun-20-2020, 10:26 PM
How do I get attribute XPATHs list ?
======================================
Thanks for reviewing my 1st thread in this forum.
I am trying to list all Xpaths of the input file using Python code.
Here is the input.
2) xpathf = root.find('.//country')
print(xpathf.get("value"))
xpathf = root.find('.//data/country/year')
print(xpathf.get("value"))
are not printing the data value of XPATHs './/country' & './/data/country/year'
I am looking to extract the value based on XPATH.
3) What is the way to extract the attribute value based on XPATHs?
4) If there is the name space spec in input file, the above code produce the XPATH list as
Thanks for your guidance.
======================================
Thanks for reviewing my 1st thread in this forum.
I am trying to list all Xpaths of the input file using Python code.
Here is the input.
Output:<?xml version="1.0" encoding="UTF-8"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2012</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
Here is the python code:import xml.etree.ElementTree as ET from lxml import etree infile = 'D:\Python_work\eclipse-workspace\My1stPythonP\CountryData.xml' output ="D:\\Python_work\\eclipse-workspace\\My1stPythonP\\outfile.out" tree = etree.parse(infile) root = tree.getroot() f = open(output,'w') #open write to file count = tree.xpath("count(.//country)") print (count) f.write("%s\n" %(count)) xpathf = root.find('.//country') print(xpathf.get("value")) xpathf = root.find('.//data/country/year') print(xpathf.get("value")) print (tree.getroot() ) xmlstr = ET.tostring(root, method='xml') root1 = ET.fromstring(xmlstr) tree1 = etree.ElementTree(root) for e in root.iter(): f.write("%s\n" %(tree1.getpath(e))) f.close()1) tree1.getpath(e) getting the list of XPATHs, but attribute XPATHS are missing from the list
2) xpathf = root.find('.//country')
print(xpathf.get("value"))
xpathf = root.find('.//data/country/year')
print(xpathf.get("value"))
are not printing the data value of XPATHs './/country' & './/data/country/year'
I am looking to extract the value based on XPATH.
3) What is the way to extract the attribute value based on XPATHs?
4) If there is the name space spec in input file, the above code produce the XPATH list as
Output:/*
/*/*[1]
/*/*[2]
/*/*[2]/*[1]
/*/*[2]/*[2]
/*/*[2]/*[3]
/*/*[2]/*[4]
/*/*[2]/*[5]
/*/*[2]/*[6]
/*/*[2]/*[7]
/*/*[2]/*[8]
/*/*[2]/*[9]
/*/*[2]/*[10]
Are there ways to get readable XPATH, when input file contain a namespace spec?Thanks for your guidance.