!

Dette materialet blir ikke lenger vedlikeholdt. Du vil finne oppdatert materiale på siden: http://borres.hiof.no/wep/

lxml
ElementPath
Børre Stenseth
Python > lxml >ElementPath

ElementPath

Hva
Søke med ElementPath

ElementPath er svært lik XPATH. ElementPath tillater namespace notasjon, men ikke sammenligninger og funksjoner.

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="http://www.it.hiof.no/~borres/commondata/olympiade/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

testing1()
testing2('JAM')
testing3()
Referanser
  1. lxml - XML and HTML with Python lxml.de/ 03-08-2011
Vedlikehold
Børre Stenseth, september 2012
( Velkommen ) Python > lxml >ElementPath ( XPath )