XPath Search with ElementTree

New in xml. XPath search for finding XML file using python format ElementTree

<root> <child>One</child> <child>Two</child> <child>Three</child> </root> 

perform a search for the child using "Two" and return true / false

if it was running as

 from elementtree import ElementTree root = ElementTree.parse(open(PathFile)).getroot() 

how can this be achieved

+4
source share
2 answers

Recently, I have been playing with ElementTree, let's see ..

 >>> from xml.etree import ElementTree >>> help(ElementTree.ElementPath) >>> root = ElementTree.fromstring(""" <root><child>One</child><child>Two</child><child>Three</child></root> """) >>> ElementTree.ElementPath.findall(root, "child") [<Element child at 2ac98c0>, <Element child at 2ac9638>, <Element child at 2ac9518>] >>> elements = ElementTree.ElementPath.findall(root, "child") >>> two = [x for x in elements if x.text == "Two"] >>> two[0].text 'Two' 

Is this what you are looking for right? He says that ElementPath has limited xpath support, but he doesn't talk about support at all.

+1
source

When the following XPath expression is evaluated:

boolean(/*/*[.='Two'])

the result is true , if such an element (a child of the upper element, such that its string value is two), exists

and false .

Hope this helps.

Greetings

Dimitar Novachev

+1
source

All Articles