执行带命名空间的 XPath 查询(SQLXML 托管类)

XPath 查询可以包含命名空间。如果架构元素为限定命名空间(使用目标命名空间),则针对该架构的 XPath 查询必须指定该命名空间。

由于 Microsoft SQLXML 4.0 中不支持使用通配符 (*),因此必须使用命名空间前缀来指定 XPath 查询。若要解析此前缀,可使用 namespaces 属性来指定命名空间绑定。

在下例中,XPath 查询通过使用通配符 (*) 以及 local-name()namespace-uri() XPath 函数来指定命名空间。此 XPath 查询将返回其本地名称为 Employee 且其命名空间 URI 为 urn:myschema:Contacts 的所有元素:

/*[local-name() = 'Contact' and namespace-uri() = 'urn:myschema:Contacts']

在 SQLXML 4.0 中,用命名空间前缀来指定此 XPath 查询。例如 x:Person,其中 x 为命名空间前缀。请看以下 XSD 架构:

<schema xmlns="http://www.w3.org/2001/XMLSchema"
            xmlns:sql="urn:schemas-microsoft-com:mapping-schema"
            xmlns:con="urn:myschema:Contacts"
            targetNamespace="urn:myschema:Contact">
<complexType name="ContactType">
  <attribute name="CID" sql:field="BusinessEntityID" type="ID"/>
  <attribute name="FName" sql:field="FirstName" type="string"/>
  <attribute name="LName" sql:field="LastName"/> 
</complexType>
<element name="Person" type="con:PersonType" sql:relation="Person.Person"/>
</schema>

由于此架构定义了目标命名空间,因此针对此架构的 XPath 查询(如“Employee”)必须包含该命名空间。

以下 C# 应用程序示例针对前述 XSD 架构 (MySchema.xml) 执行 XPath 查询。若要解析此前缀,请通过使用 SqlXmlCommand 对象的 Namespaces 属性来指定命名空间绑定。

注意注意

在该代码中,必须在连接字符串中提供 SQL Server 实例的名称。

using System;
using Microsoft.Data.SqlXml;
using System.IO;
class Test
{
      static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks2008R2;Integrated Security=SSPI";
      public static int testXPath()
      {
         //Stream strm;
         SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
         cmd.CommandText = "x:Contact[@CID='1']";
         cmd.CommandType = SqlXmlCommandType.XPath;
         cmd.RootTag = "ROOT";
         cmd.Namespaces = "xmlns:x='urn:myschema:ContactsContact'";
         cmd.SchemaPath = "MySchema.xml";
         using (Stream strm = cmd.ExecuteStream()){
            using (StreamReader sr = new StreamReader(strm)){
               Console.WriteLine(sr.ReadToEnd());
            }
         }
         return 0;
      }
      public static int Main(String[] args)
      {
         testXPath();
         return 0;
      }
   }

测试应用程序

  1. 确保已在计算机上安装了 Microsoft .NET Framework。它是测试此示例所必需的。

  2. 将在该示例中提供的 XSD 架构 (MySchema.xml) 保存到某个文件夹中。

  3. 将在该示例中提供的 C# 代码 (DocSample.cs) 保存到存储架构的相同文件夹中。(如果将文件存储在其他文件夹中,则必须编辑代码并为映射架构指定相应的目录路径。)

  4. 编译代码。若要在命令提示符下编译此代码,请使用:

    csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
    

    这将创建一个可执行文件 (DocSample.exe)。

  5. 在命令提示符下,执行 DocSample.exe。