ElementPath
De aktuelle dataene er ordnet i en XML-fil: all_results.xml
Kopier datafila og pythonkoden nedenfor og eksperimenter.
Eksempel
from lxml import etree """ Selecting the names of all athlets from JAMAICA by a Elementpath (allmost like XPATH) No attempt to remove duplicates """ xmlfile="../lxml/all_results.xml" #xmlfile="all_results.xml" def testing1(): tree=etree.parse(xmlfile) names=tree.findall(".//athlet[nation='JAM']/name") for n in names: print (n.text) """ Selecting the names of all athlets from a country given as parameter, remove duplicates and sort """ def testing2(country): tree=etree.parse(xmlfile) path=".//athlet[nation='%s']/name"%country names=tree.findall(path) result=[] for n in names: if result.count(n.text)==0: result.append(n.text) result.sort() print (result) """ Selecting all names as textcontent of name tags identified by iterating a Elementpath thorughout the tree """ def testing3(): tree=etree.parse(xmlfile) names=[b.text for b in tree.iterfind(".//name")] result=[] for n in names: if result.count(n)==0: result.append(n) result.sort() for r in result: print (r) print('------- testing1 --------') testing1() print('------- testing2 --------') testing2('JAM') print('------- testing2 --------') testing3()