使用XPath获取属性

2024-04-25 19:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

给定这样的XML结构:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>

如何获取第一个元素的值lang(其中lang是书名中的eng)?


Tags: langtitleversionisoxml结构priceeng
3条回答

How could I get the value of lang (where lang=eng in book title), for the first element?

使用

/*/book[1]/title/@lang

这意味着:

选择title元素的lang属性,该元素是XML文档顶部元素的第一个book子元素的子元素。

要仅获取此属性的字符串值,请使用标准的XPath函数string()

string(/*/book[1]/title/@lang)

谢谢!这解决了我在Div中使用data属性时遇到的类似问题

<div id="prop_sample" data-want="data I want">data I do not want</div>

使用这个xpath://*[@id="prop_sample"]/@data-want

希望这能帮助别人!

您可以尝试下面的xPath模式

  XPathExpression expr = xPath.compile("/bookstore/book/title[@lang='eng']")

相关问题 更多 >

    热门问题