[英]Find an xml element with some specific text using xpath or find in python using lxml
我试图找到所有具有值abc
book
元素,即name
标签值。 我用过xpath:
val= xml1.xpath('//bookstore/book/name[text()="abc"]')
但它正在返回无。
<bookstore>
<book>
<name>abc</name>
<price>30</price>
</book>
<book>
<name>Learning XML</name>
<price>56</price>
</book>
</bookstore>
为书签添加了Id属性。
root.xpath("//bookstore/book/name[text()='abc']
它将给出所有name
元素的列表,其中text
是abc
而不是父元素。
检查以下内容
>>> 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初学者:
name
标签。 name
标签的text
等于abc
。 name
标签的父级并附加到list变量。 码:
>>> 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'}
这是一种方法:
from lxml import etree
# Create an ElementTree instance
tree = etree.parse("bookstore.xml")
# Get all 'book' elements that have a 'name' child with a string value of 'abc'
books = tree.xpath('book[name="abc"]')
# Print name and price of those books
for book in books:
print book.find("name").text, book.find("price").text
在问题中使用XML时的输出:
abc 30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.