XPath search with ElementTree

New to xml. Looking for XPath to search a xml file with python ElementTree format

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

to do search for child with "Two" and return true/false

if it was started off like

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

how can this be achieved


Asked by: First Name937 | Posted: 28-01-2022






Answer 1

I've been playing with ElementTree lately, lets 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'

This is what you look for right? It says ElementPath has just limited xpath support though, but it does not say not support at all.

Answered by: Aida752 | Posted: 01-03-2022



Answer 2

When the following XPath expression is evaluated:

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

the result is true, if such an element (a child of the top element such that its string value is equal to "Two") exists,

and false otherwise.

Hope this helped.

Cheers,

Dimitre Novatchev

Answered by: Lily876 | Posted: 01-03-2022



Similar questions

python - HTML inside node using ElementTree

I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows: &lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; &lt;/Course&gt; Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's description, so I do: desc = _course...


python - Using XPath in ElementTree

My XML file looks like the following: &lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19"&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;Of...


python - insert tags in ElementTree text

I am using the Python ElementTree module to manipulate HTML. I want to emphasize certain words, and my current solution is: for e in tree.getiterator(): for attr in 'text', 'tail': words = (getattr(e, attr) or '').split() change = False for i, word in enumerate(words): word = clean_word.s...


python - How do I create new xml from ElementTree?

Bit of a beginner question here: Say I have a block of xml: &lt;root&gt; &lt;district&gt; &lt;house&gt;&lt;room&gt;&lt;door/&gt;&lt;room&gt;&lt;/house&gt; &lt;/district&gt; &lt;district&gt; &lt;street&gt; &lt;house&gt;and so on&lt;/house&gt; &lt;/street&gt; etc. With ElementTree I can do: houses=doc.findall(".//house") to select...


Can Python xml ElementTree parse a very large xml file?

I'm trying to parse a large file (> 2GB) of structured markup data and the memory is not enough for this.Which is the optimal way of XML parsing class for this condition.More details please.


python - How to parse shrink the web xml with ElementTree

I am trying to use the shrink the web service for site thumbnails. They have a API that returns XML telling you if the site thumbnail can be created. I am trying to use ElementTree to parse the xml, but not sure how to get to the information I need. Here is a example of the XML response: &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;stw:ThumbnailResponse xmlns:stw="http://www.shrinktheweb.com/doc/stw...


python ElementTree find child with certain text value

I've been searching for a while. Is there a way to directly retrieve a child based on the text value of a tag? For example: &lt;a&gt; &lt;b&gt; &lt;c&gt;h&lt;/c&gt; &lt;/b&gt; &lt;b&gt; &lt;c&gt;j&lt;/c&gt; &lt;/b&gt; &lt;/a&gt; And say I want to retrieve the child be whose "c" text value == j. Is there a way of doing this other than having to get all the...


python - How to save ElementTree as UTF-16

I'm trying to save an XML file encoded as UTF-16 with cElementTree. This is the same project, but different than the DOCTYPE issue in: How to create &lt;!DOCTYPE&gt; with Python&#39;s cElementTree I've learned that if I do not declare the encoding in the string, cElementTree will add it. So, the code is like th...


python - How do I query in ElementTree as in Xpath?

This is a sample query I might do in PHP: foreach(steps as step) { areT_eles = xpath-&gt;query(t_eleQuery, step) } Now in python: for step in index steps: areT_eles = ?!?!?!?!!??!?!!??!! I tried this: for step in index steps: areT_eles = xpath.query(t_eleQuery, step) It didn't work. I've only imported Elementtree fr...


python - Saving XML files using ElementTree

I'm trying to develop simple Python (3.2) code to read XML files, do some corrections and store them back. However, during the storage step ElementTree adds this namespace nomenclature. For example: &lt;ns0:trk&gt; &lt;ns0:name&gt;ACTIVE LOG&lt;/ns0:name&gt; &lt;ns0:trkseg&gt; &lt;ns0:trkpt lat="38.5" lon="-120.2"&gt; &lt;ns0:ele&gt;6.385864&lt;/ns0:ele&gt; &lt;ns0:time&gt;2011-12-10T17:46:30...


python - HTML inside node using ElementTree

I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows: &lt;Course&gt; &lt;Description&gt;Line 1&lt;br /&gt;Line 2&lt;/Description&gt; &lt;/Course&gt; Now, supposing _course is an Element variable which hold this Couse element. I want to access this course's description, so I do: desc = _course...


How to create "virtual root" with Python's ElementTree?

I am trying to use Python's ElementTree to generate an XHTML file. However, the ElementTree.Element() just lets me create a single tag (e.g., HTML). I need to create some sort of a virtual root or whatever it is called so that I can put the various , DOCTYPES, etc. How do I do that? Thanks


python - Using XPath in ElementTree

My XML file looks like the following: &lt;?xml version="1.0"?&gt; &lt;ItemSearchResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2008-08-19"&gt; &lt;Items&gt; &lt;Item&gt; &lt;ItemAttributes&gt; &lt;ListPrice&gt; &lt;Amount&gt;2260&lt;/Amount&gt; &lt;/ListPrice&gt; &lt;/ItemAttributes&gt; &lt;Offers&gt; &lt;Offer&gt; &lt;Of...


xml - Alter namespace prefixing with ElementTree in Python

By default, when you call ElementTree.parse(someXMLfile) the Python ElementTree library prefixes every parsed node with it's namespace URI in Clark's Notation: {http://example.org/namespace/spec}mynode This makes accessing specific nodes by name a huge pain later in the code. I've read through the docs on ElementTree and namespaces and it looks like the iterparse() function sh...


elementtree - How to use "class" the word as parameter function calls in python

I am writing an XML generator per my manager's request. For less typings' sake, I decided using ElementTree as parser and SimpleXMLWriter as writer. The result XML require attributes named "class". e.g. &lt;Node class="oops"&gt;&lt;/Node&gt; As the official tutorial suggested, to write an XML node just use this method: w.element("meta", name="generator", value="my ...


python - insert tags in ElementTree text

I am using the Python ElementTree module to manipulate HTML. I want to emphasize certain words, and my current solution is: for e in tree.getiterator(): for attr in 'text', 'tail': words = (getattr(e, attr) or '').split() change = False for i, word in enumerate(words): word = clean_word.s...


Read XML with multiple top-level items using Python ElementTree?

How can I read an XML file using Python ElementTree, if the XML has multiple top-level items? I have an XML file that I would like to read using Python ElementTree. Unfortunately, it has multiple top-level tags. I would wrap &lt;doc&gt;...&lt;/doc&gt; around the XML, except I have to put the &lt;doc&gt; after the &lt;?xml&gt; and &lt;!DOCTYPE&gt;...


python - How do I create new xml from ElementTree?

Bit of a beginner question here: Say I have a block of xml: &lt;root&gt; &lt;district&gt; &lt;house&gt;&lt;room&gt;&lt;door/&gt;&lt;room&gt;&lt;/house&gt; &lt;/district&gt; &lt;district&gt; &lt;street&gt; &lt;house&gt;and so on&lt;/house&gt; &lt;/street&gt; etc. With ElementTree I can do: houses=doc.findall(".//house") to select...


python - : in node causing Keyerror in xmlparsing using ElementTree

Hi I'm using ElementTree to parse out an xml feed from Kuler. I'm only beginning in python but am stuck here. The parsing works fine until I attempt to retrieve any nodes containing ':' e.g kuler:swatchHexColor Below is a cut down version of the full feed but same structure: &lt;rss xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:kuler="http://kuler.adobe.com/kuler/API/rss/" xmlns:rss="http://blog...


python - Passing around an ElementTree

In my program, I need to make use of an ElementTree object in various functions in my program. More specifically, I am doing this: tree = etree.parse('somefile.xml') I am passing this tree around in my program. I was wondering whether this is a good approach, or can I do this: Create a global tree (I come from a C++ background and I know global is bad)






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top