繁体   English   中英

使用xpath查找包含某些特定文本的xml元素,或使用lxml在python中查找

[英]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元素的列表,其中textabc而不是父元素。

检查以下内容

>>> 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初学者:

  1. 从该数据创建解析对象。
  2. 定义父列表变量。
  3. 迭代name标签。
  4. 检查name标签的text等于abc
  5. 如果是,则获取name标签的父级并附加到list变量。
  6. 显示结果:

码:

>>> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM