XPath 查询可以包含命名空间。 如果架构元素具有命名空间限定(即,如果包含目标命名空间),则针对架构的 XPath 查询必须指定此命名空间。
由于 SQLXML 4.0 不支持使用通配符 \ ,因此必须使用命名空间前缀指定 XPath 查询。 若要解析此前缀,请使用命名空间属性指定命名空间绑定。
在下面的示例中,XPath 查询使用通配符 \ 和 local-name() 和 namespace-uri() XPath 函数指定命名空间。 此 XPath 查询返回本地名称所在的 Contact 所有元素,并且命名空间 URI 为 urn:myschema:Contacts。
/*[local-name() = 'Contact' and namespace-uri() = 'urn:myschema:Contacts']
在 SQLXML 4.0 中,必须使用命名空间前缀指定此 XPath 查询。 例如 x:Contact,命名空间前缀在哪里 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:Contacts">
<complexType name="ContactType">
<attribute name="CID" sql:field="ContactID" type="ID"/>
<attribute name="FName" sql:field="FirstName" type="string"/>
<attribute name="LName" sql:field="LastName"/>
</complexType>
<element name="Contact" type="con:ContactType" sql:relation="Person.Contact"/>
</schema>
由于此架构定义了目标命名空间,因此针对架构的 XPath 查询(如“Employee”)必须包含命名空间。
这是针对上述 XSD 架构执行 XPath 查询(x:Employee)的示例Microsoft Visual Basic 应用程序。 若要解析前缀,命名空间绑定是使用命名空间属性指定的。
注释
在代码中,必须在连接字符串中提供 SQL Server 实例的名称。 此外,此示例指定对数据提供程序使用 SQL Server Native Client (SQLNCLI11),这需要安装其他网络客户端软件。 有关详细信息,请参阅 SQL Server Native Client 的系统要求。
Option Explicit
Private Sub Form_Load()
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim stm As New ADODB.Stream
con.Open "provider=SQLXMLOLEDB.4.0;Data Provider=SQLNCLI11;Data Source=SqlServerName;Initial Catalog=AdventureWorks;Integrated Security=SSPI;"
Set cmd.ActiveConnection = con
stm.Open
cmd.Properties("Output Stream").Value = stm
cmd.Properties("Output Encoding") = "utf-8"
cmd.Properties("Mapping schema") = "C:\DirectoryPath\con-ex.xml"
cmd.Properties("namespaces") = "xmlns:x='urn:myschema:Contacts'"
' Debug.Print "Set Command Dialect to DBGUID_XPATH"
cmd.Dialect = "{ec2a4293-e898-11d2-b1b7-00c04f680c56}"
cmd.CommandText = "x:Contact"
cmd.Execute , , adExecuteStream
stm.Position = 0
Debug.Print stm.ReadText(adReadAll)
End Sub
测试此应用程序
将示例 XSD 架构保存在文件夹中。
创建 Visual Basic 可执行项目,并将代码复制到其中。 根据需要更改指定的目录路径。
添加以下项目引用:
"Microsoft ActiveX Data Objects 2.8 Library"执行应用程序。
下面是部分结果:
<y0:Employee xmlns:y0="urn:myschema:Contacts"
LName="Achong" CID="1" FName="Gustavo"/>
<y0:Employee xmlns:y0="urn:myschema:Employees"
LName="Abel" CID="2" FName="Catherine"/>
XML 文档中生成的前缀是任意的,但它们映射到同一命名空间。