XPath函数示例:提供一些使用XPath函数的实际示例,包括从文档中选择特定的元素、计算元素值的总和、提取文本数据等。
- 选择特定的元素
假设我们有以下XML文档:
<catalog> <book id="001"> <title>The Great Gatsby</title> <author>F. Scott Fitzgerald</author> <year>1925</year> </book> <book id="002"> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <year>1960</year> </book> <book id="003"> <title>1984</title> <author>George Orwell</author> <year>1949</year> </book> </catalog>
我们想要选择 id
属性值为 002
的书籍元素。使用XPath函数 @
可以选择属性,如下所示:
/catalog/book[@id="002"]
上述XPath表达式将选择以下元素:
<book id="002"> <title>To Kill a Mockingbird</title> <author>Harper Lee</author> <year>1960</year> </book>
- 计算元素值的总和
假设我们有以下XML文档:
<numbers> <number>10</number> <number>20</number> <number>30</number> </numbers>
我们想要计算所有 number
元素的值的总和。使用XPath函数 sum()
可以实现该功能,如下所示:
sum(/numbers/number)
上述XPath表达式将返回 60
。
- 提取文本数据
假设我们有以下XML文档:
<story> <intro>Welcome to pidancode.com</intro> <chapter> <title>Chapter 1: Introduction</title> <paragraph>皮蛋编程 is a website that offers free tutorials on various programming languages and technologies.</paragraph> <paragraph>Whether you are a beginner or an experienced programmer, you can find valuable resources on our website.</paragraph> </chapter> <chapter> <title>Chapter 2: Getting Started with Python</title> <paragraph>In this chapter, we will introduce the basics of Python programming and show you how to write your first Python program.</paragraph> <paragraph>By the end of the chapter, you will have a good understanding of Python syntax and be ready to tackle more advanced topics.</paragraph> </chapter> </story>
我们想要提取第二个 chapter
元素中的第一个 paragraph
元素的文本数据。使用XPath函数 text()
可以提取元素的文本数据,如下所示:
/story/chapter[2]/paragraph[1]/text()
上述XPath表达式将返回:
In this chapter, we will introduce the basics of Python programming and show you how to write your first Python program.
相关文章