Added Id attribute to book tag.
root.xpath("//bookstore/book/name[text()='abc'] it will give list of all name element which text is abc not parent element.
check following:
>>> data = """<bookstore>
... <book id="1">
... <name>abc</name>
... <price>30</price>
... </book>
... <book id="2">
... <name>Learning XML</name>
... <price>56</price>
... </book>
... </bookstore> """
>>> root = PARSER.fromstring(data)
>>> root.xpath("//bookstore/book")
[<Element book at 0xb726d144>, <Element book at 0xb726d2d4>]
>>> root.xpath("//bookstore/book/name[text()='abc']")
[<Element name at 0xb726d9b4>]
>>> root.xpath("//bookstore/book/name[text()='abc']/parent::*")
[<Element book at 0xb726d7d4>]
>>> root.xpath("//bookstore/book/name[text()='abc']/parent::*")[0].attrib
{'id': '1'}
Python beginner:
- Create Parsing Object from that data.
- Define parent list variable.
- Iterate on
name tags.
- Check
text of name tag is equal to abc.
- if yes, then get parent of
name tag and append to list variable.
- Display result:
code:
>>> root = PARSER.fromstring(data)
>>> abc_parent = []
>>> for i in root.getiterator("name"):
... if i.text=="abc":
... abc_parent.append(i.getparent())
...
>>> print abc_parent
[<Element book at 0xb726d2d4>]
>>> abc_parent[0].attrib
{'id': '1'}
nameelements. My interpretation is that the OP wantsbookelements that have anamechild with a specific value.