【问题标题】:Find an xml element with some specific text using xpath or find in python using lxml使用 xpath 查找具有某些特定文本的 xml 元素,或使用 lxml 在 python 中查找
【发布时间】:2015-02-26 06:29:36
【问题描述】:

我正在尝试查找所有具有 abc 值的 book 元素,即 name 标记值。我用过xpath:

val= xml1.xpath('//bookstore/book/name[text()="abc"]')

但它返回 None。

<bookstore>
 <book>
   <name>abc</name>
   <price>30</price>
 </book>
 <book>
   <name>Learning XML</name>
   <price>56</price>
 </book>
</bookstore> 

【问题讨论】:

  • 据我所知,发布的 XPath 应该可以工作。也许问题是您的实际 XML 具有默认命名空间,不是吗?
  • 问题中的 XPath 选择了 name 元素。我的解释是,OP 想要 book 元素的 name 子元素具有特定值。

标签: python xpath lxml


【解决方案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

【讨论】:

    【解决方案2】:

    为书籍标签添加了 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. 检查textname 标签是否等于abc
    5. 如果是,则获取name 标记的父级并附加到列表变量。
    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'}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2014-03-21
      相关资源
      最近更新 更多