我试图找到所有具有值abc的书元素,即名称标签值.我用过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>
解决方法:
这是一种方法:
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