XML 的 XPath 语法

XPath 是 XML 路径语言(XML Path Language),用来确定XML文档中某部分位置的语言。无论是什么语言什么框架,几乎都可以使用 XPath 来高效查询 XML 文件。

本文将介绍 XPath 的一些语法。


本文读写的 XML 文件会以 文章末尾的代码 - 假设的 XML 文件 作为示例。

XPath 被称作 XML 路径语言,正出自于其最重要的 —— 路径表达式。

路径

其实,上面的那些语法都是简写形式的语法,如果将它们完整写出来,将是这样的形式:

这里的 childdescendant-or-self 是轴描述语法,除了这两个,还有这些:

对于 attribute 的使用,例如 //repository/@type 查找任意位置的 repository 节点的 type 属性。

节点类型

在前面的路径中,我们已经使用了 node() 来寻找元素节点,除 node() 表达式之外,还有:

节点内容

使用中括号来描述节点的内容。

例如 //repository[@type='git'] 用来查找任意位置的 repository 节点,并且它有一个 type 属性值为 git

中括号是可以写多个的,例如:

运算符

更多函数

w3c 对 XPath 支持的函数有详细的查询页面,可以访问 XPath and XQuery Functions and Operators 3.1 查询。

在 .NET 中使用 XPath 语法

在 .NET 中使用 XPath 语法可以参考我的另一篇文章:.NET 使用 XPath 来读写 XML 文件


假设的 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>MSTestEnhancer</id>
    <version>1.6.0</version>
    <authors>walterlv</authors>
    <owners>walterlv</owners>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <licenseUrl>https://github.com/easiwin/MSTestEnhancer/blob/master/LICENSE</licenseUrl>
    <projectUrl>https://easiwin.github.io/mstest-enhancer</projectUrl>
    <iconUrl>https://easiwin.github.io/mstest-enhancer/icon.png</iconUrl>
    <description>MSTestEnhancer helps you to write unit tests without naming any method. You can write method contract descriptions instead of writing confusing test method name when writing unit tests.</description>
    <releaseNotes>Support passing null into WithArgument method.</releaseNotes>
    <copyright>Copyright (c) 2018 dotnet职业技术学院</copyright>
    <repository type="git" url="https://github.com/easiwin/MSTestEnhancer.git" />
    <dependencies>
      <group targetFramework=".NETFramework4.5">
        <dependency id="MSTest.TestFramework" version="1.2.0" exclude="Build,Analyzers" />
        <dependency id="System.ValueTuple" version="4.4.0" exclude="Build,Analyzers" />
      </group>
      <group targetFramework=".NETFramework4.7">
        <dependency id="MSTest.TestFramework" version="1.2.0" exclude="Build,Analyzers" />
      </group>
      <group targetFramework=".NETStandard2.0">
        <dependency id="MSTest.TestFramework" version="1.2.0" exclude="Build,Analyzers" />
      </group>
    </dependencies>
  </metadata>
</package>

参考资料

本文会经常更新,请阅读原文: https://blog.walterlv.com/post/xml-xpath.html ,以避免陈旧错误知识的误导,同时有更好的阅读体验。

如果你想持续阅读我的最新博客,请点击 RSS 订阅,或者前往 CSDN 关注我的主页

知识共享许可协议 本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可。欢迎转载、使用、重新发布,但务必保留文章署名 吕毅 (包含链接: https://blog.walterlv.com ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请 与我联系 (walter.lv@qq.com)