在 Linux 命令列中評估 XPath 表示式


介紹

XPath 是一種強大的語言,用於在 XML 文件中導航和選擇元素。它通常與 XSLT (用於轉換 XML 文件的語言) 結合使用,以從文件中提取特定資訊。本文將討論如何在 Linux 命令列中使用命令列工具 xmllint 來評估 XPath 表示式。

安裝 xmllint

在開始在 Linux 命令列中評估 XPath 表示式之前,我們必須首先安裝 xmllint。xmllint 是 libxml2 庫的一部分,大多數 Linux 發行版都包含該庫。要檢查系統中是否已安裝 xmllint,請開啟終端並鍵入“xmllint --version”。如果未安裝 xmllint,可以使用 Linux 發行版的包管理器安裝它。例如,在 Ubuntu 上,可以使用命令“sudo apt-get install libxml2-utils”安裝它。

評估 XPath 表示式

安裝 xmllint 後,我們就可以開始在 Linux 命令列中評估 XPath 表示式了。使用 xmllint 評估 XPath 表示式的基本語法如下:

xmllint --xpath "expression" file.xml

其中,“expression”是要評估的 XPath 表示式,“file.xml”是要搜尋的 XML 文件。

示例

例如,假設我們有以下名為“example.xml”的 XML 文件:

<?xml version="1.0"?> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</titl> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J. K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</auth> <year>2003</year> <price>49.99</price> </book> </bookstore>

如果我們想選擇文件中的所有 book 元素,可以使用以下 XPath 表示式:

xmllint --xpath "//book" example.xml

輸出

這將返回以下輸出:

<book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book> <book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J. K. Rowling</author> <year>2005</year> <price>29.99</price> </book> <book category="WEB"> <title lang="en">XQuery Kick Start</title> <author>James McGovern</author> <author>Per Bothner</author> <author>Kurt Cagle</author> <author>James Linn</author> <author>Vaidyanathan Nagarajan</author> <year>2003</year> <price>49.99</price> </book> ```

我們還可以使用 XPath 選擇文件中的特定元素。例如,如果我們想選擇所有由 J. K. Rowling 撰寫的書籍的標題,可以使用以下 XPath 表示式:

示例

xmllint --xpath "//book[author='J. K. Rowling']/title" example.xml

輸出

這將返回以下輸出:

<title lang="en">Harry Potter</title>

我們還可以使用 XPath 根據屬性值選擇元素。例如,如果我們想選擇“COOKING”類別中的所有書籍,可以使用以下 XPath 表示式:

示例

xmllint --xpath "//book[@category='COOKING']" example.xml

輸出

這將返回以下輸出:

<book category="COOKING"> <title lang="en">Everyday Italian</title> <author>Giada De Laurentiis</author> <year>2005</year> <price>30.00</price> </book>

我們還可以使用 XPath 根據元素在文件中的位置選擇特定元素。例如,如果我們想選擇文件中的第二個 book 元素,可以使用以下 XPath 表示式:

示例

xmllint --xpath "(//book)[2]" example.xml

輸出

這將返回以下輸出:

<book category="CHILDREN"> <title lang="en">Harry Potter</title> <author>J. K. Rowling</author> <year>2005</year> <price>29.99</price> </book>

結論

XPath 是一種強大的語言,用於在 XML 文件中導航和選擇元素。在本文中,我們討論瞭如何使用命令列工具 xmllint 在 Linux 命令列中評估 XPath 表示式。我們還介紹了一些根據元素的位置、屬性值及其子元素的值選擇元素的基本示例。掌握這些基本概念後,您現在可以使用 xmllint 從 Linux 命令列中的 XML 文件中提取特定資訊。

更新於:2023年1月27日

2K+ 瀏覽量

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.