Download SQLXML Managed Classes

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Microsoft Access wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Clusterpoint wikipedia , lookup

Team Foundation Server wikipedia , lookup

Database model wikipedia , lookup

Relational model wikipedia , lookup

Versant Object Database wikipedia , lookup

Open Database Connectivity wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

PL/SQL wikipedia , lookup

Transcript
Table of Contents
Accessing SQLXML Functionality in the .NET Environment
Applying an XSL Transformation (SQLXML Managed Classes)
Executing SQL Queries (SQLXML Managed Classes)
Executing SQL Queries by Using the ExecuteXMLReader Method
Executing Template Files by Using the CommandStream Property
Executing Template Files by Using the CommandText Property
Executing XPath Queries (SQLXML Managed Classes)
Executing XPath Queries with Namespaces (SQLXML Managed Classes)
Processing XML on the Client Side (SQLXML Managed Classes)
SQLXML 4.0 .NET Framework Support - Managed Classes
SQLXML Managed Classes - SqlXmlAdapter Object
SQLXML Managed Classes - SqlXmlCommand Object
SQLXML Managed Classes - SqlXmlParameter Object
Accessing SQLXML Functionality in the .NET
Environment
3/24/2017 • 1 min to read • Edit Online
This example shows:
How to use Microsoft SQLXML Managed Classes (Microsoft.Data.SqlXml) to access Microsoft SQL Server in
the Microsoft .NET Framework environment.
How DiffGrams that are generated in the .NET Framework environment can apply data updates to SQL
Server tables.
In this application, an XPath query is executed against an XSD schema. The execution of the XPath query
returns an XML document that consists of contact data (FirstName, LastName). The application loads the
XML document in the dataset in the .NET Framework environment. The data in the dataset is modified: the
contact's first name is changed to "Susan" for the first contact in the dataset. The DiffGram is generated
from the dataset, and the update that is specified in the DiffGram (the change in the employee's first name)
is then applied to the Person.Contact table.
NOTE
In the code, you must provide the name of the instance of SQL Server in the connection string.
using System;
using System.Data;
using Microsoft.Data.SqlXml;
using System.IO;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=SqlServerName;database=AdventureWorks;Integrated
Security=SSPI;";
public static int testParams()
{
DataRow row;
SqlXmlAdapter ad;
//need a memory stream to hold diff gram temporarily
MemoryStream ms = new MemoryStream();
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.RootTag = "ROOT";
cmd.CommandText = "Con";
cmd.CommandType = SqlXmlCommandType.XPath;
cmd.SchemaPath = "MySchema.xml";
//load data set
DataSet ds = new DataSet();
ad = new SqlXmlAdapter(cmd);
ad.Fill(ds);
row = ds.Tables["Con"].Rows[0];
row["FName"] = "Susan";
ad.Update(ds);
return 0;
}
public static int Main(String[] args)
{
testParams();
return 0;
}
}
To test the example:
To test this example, you must have the Microsoft .NET Framework installed on your computer.
1. Save this XSD schema (MySchema.xml) in a folder:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="Con" sql:relation="Person.Contact" >
<xsd:complexType>
<xsd:sequence>
<xsd:element name="FName"
sql:field="FirstName"
type="xsd:string" />
<xsd:element name="LName"
sql:field="LastName"
type="xsd:string" />
</xsd:sequence>
<xsd:attribute name="ContactID" type="xsd:integer" />
</xsd:complexType>
</xsd:element>
</xsd:schema>
2. Save the C# code (DocSample.cs) provided in this example in the same folder in which the schema is stored.
(If you store the files in a different folder, you will have to edit the code and specify the appropriate
directory path for the mapping schema.)
3. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
At the command prompt, execute DocSample.exe.
Applying an XSL Transformation (SQLXML Managed
Classes)
3/24/2017 • 2 min to read • Edit Online
In this example, an SQL query is executed against the AdventureWorks database. The XSL transformation is applied
to the query result to generate a two-column table of the employees' first and last names.
The XslPath property of the SqlXmlCommand object is used to specify the XSL file and its directory path.
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
using
using
using
class
{
System;
Microsoft.Data.SqlXml;
System.IO;
Test
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testXSL()
{
//Stream strm;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandText = "SELECT TOP 20 FirstName, LastName FROM Person.Contact FOR XML AUTO";
cmd.XslPath = "MyXSL.xsl";
cmd.RootTag = "root";
using (Stream strm = cmd.ExecuteStream()){
using (StreamReader sr = new StreamReader(strm)){
Console.WriteLine(sr.ReadToEnd());
}
}
return 0;
}
public static int Main(String[] args)
{
testXSL();
return 0;
}
}
This is the XSL style sheet you can use to test the application:
<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match = '*'>
<xsl:apply-templates />
</xsl:template>
<xsl:template match = 'Person.Contact'>
<TR>
<TD><xsl:value-of select = '@FirstName' /></TD>
<TD><B><xsl:value-of select = '@LastName' /></B></TD>
</TR>
</xsl:template>
<xsl:template match = '/'>
<HTML>
<HEAD>
<STYLE>th { background-color: #CCCCCC }</STYLE>
</HEAD>
<BODY>
<TABLE border='1' style='width:300;'>
<TR><TH colspan='2'>Contacts</TH></TR>
<TR><TH >First name</TH><TH>Last name</TH></TR>
<xsl:apply-templates select = 'root' />
</TABLE>
</BODY>
</HTML>
</xsl:template>
</xsl:stylesheet>
To test this example, you must have the Microsoft .NET Framework installed on your computer.
To test the application
1. Save the XSL style sheet in a file (MyXSL.xsl).
2. Save the C# code (DocSample.cs) that is provided in this example in the same folder in which the style sheet
is stored.
3. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
4. At the command prompt, execute DocSample.exe.
Applying an XSL Transformation in the .NET Framework
Instead of applying an XSL transformation in the middle tier, as described previously, you can apply an XSL
transformation on the client side (in the .NET Framework). The following revised C# code shows how the XSL
transformation is applied in the .NET Framework.
NOTE
In the code, you must provide the name of the instance of SQL Server in the connection string.
using
using
using
using
using
using
System;
System.Xml;
Microsoft.Data.SqlXml;
System.IO;
System.Xml.XPath;
System.Xml.Xsl;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testXSL()
{
//Stream strm;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandText = "SELECT TOP 20 FirstName, LastName FROM Person.Contact FOR XML AUTO";
cmd.RootTag = "root";
using (Stream strm = cmd.ExecuteStream()){
XmlReader reader = new XmlReader(strm);
XPathDocument xd = new XPathDocument(reader, XmlSpace.Preserve);
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load("MyXSL.xsl");
XmlWriter writer = XmlWriter.Create("xslt_output.html");
xslt.Transform(xd, writer);
reader.Close();
writer.Close();
}
return 0;
}
public static int Main(String[] args)
{
testXSL();
return 0;
}
}
Executing SQL Queries (SQLXML Managed Classes)
3/24/2017 • 2 min to read • Edit Online
This example demonstrates:
Creating parameters (SqlXmlParameter objects).
Assigning values to the properties (Name and Value) of SqlXmlParameter objects.
In this example, a simple SQL query is executed to retrieve the first name, last name, and birth date of the
employee whose last name value is passed as a parameter. In specifying the parameter (LastName), only
the Value property is set. The Name property is not set, because in this query the parameter is positional
and no name is required.
The CommandType property of the SqlXmlCommand object by default is Sql. Therefore, the property is not
explicitly set.
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
This is the C# code:
using System;
using Microsoft.Data.SqlXml;
using System.IO;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testParams()
{
Stream strm;
SqlXmlParameter p;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandText = "SELECT FirstName, LastName FROM Person.Contact WHERE LastName=? For XML Auto";
p = cmd.CreateParameter();
p.Value = "Achong";
string strResult;
try
{
strm = cmd.ExecuteStream();
strm.Position = 0;
using(StreamReader sr = new StreamReader(strm))
{
Console.WriteLine(sr.ReadToEnd());
}
}
catch (SqlXmlException e)
{
//in case of an error, this prints error returned.
e.ErrorStream.Position=0;
strResult=new StreamReader(e.ErrorStream).ReadToEnd();
System.Console.WriteLine(strResult);
}
return 0;
}
public static int Main(String[] args)
{
testParams();
return 0;
}
}
To test the application
1. Save the C# code (DocSample.cs) provided in this topic in a folder.
2. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
3. At the command prompt, execute DocSample.exe.
To test this example, you must have the Microsoft .NET Framework installed on your computer.
Instead of specifying SQL queries as the command text, you can specify a template (as shown in the
following code fragment) that executes an updategram (which is also a template) to insert a customer
record. You can specify templates and updategrams in files and execute files. For more information, see
Executing Template Files by Using the CommandText Property.
SqlXmlCommand cmd = new SqlXmlCommand("Provider=SQLOLEDB;Data Source=SqlServerName;Initial Catalog=Database;
Integrated Security=SSPI;");
Stream stm;
cmd.CommandType = SqlXmlCommandType.UpdateGram;
cmd.CommandText = "<ROOT xmlns:sql='urn:schemas-microsoft-com:xml-sql' xmlns:updg='urn:schemas-microsoftcom:xml-updategram'>" +
"<updg:sync>" +
"<updg:before/>" +
"<updg:after>" +
"<Customer CustomerID='aaaaa' CustomerName='Some Name' CustomerTitle='SomeTitle' />" +
"</updg:after>" +
"</updg:sync>" +
"</ROOT>";
stm = cmd.ExecuteStream();
stm = null;
cmd = null;
Using ExecuteToStream
If you have an existing stream, you can use the ExecuteToStream method instead of creating a Stream object and
using the Execute method. The code from the preceding example is revised here to use the ExecuteToStream
method:
using System;
using Microsoft.Data.SqlXml;
using System.IO;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=SqlServerName;database=AdventureWorks;Integrated
Security=SSPI;";
public static int testParams()
{
SqlXmlParameter p;
MemoryStream ms = new MemoryStream();
StreamReader sr = new StreamReader(ms);
ms.Position = 0;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandText = "select FirstName, LastName from Person.Contact where LastName = ? For XML Auto";
p = cmd.CreateParameter();
p.Value = "Achong";
cmd.ExecuteToStream(ms);
ms.Position = 0;
Console.WriteLine(sr.ReadToEnd());
return 0;
}
public static int Main(String[] args)
{
testParams();
return 0;
}
}
NOTE
You can also use the ExecuteXMLReadermethod that returns an XmlReader object. For more information, see Executing SQL
Queries by Using the ExecuteXMLReader Method.
Executing SQL Queries by Using the
ExecuteXMLReader Method
3/24/2017 • 1 min to read • Edit Online
Instead of using the ExecuteToStream method, you can use the ExecuteXmlReader method of the SqlXmlCommand
object to execute commands. This method returns an XmlReader object that can be used for further processing of
the result (which in this example is printing the element or attribute names and the values).
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
using System;
using Microsoft.Data.SqlXml;
using System.IO;
using System.Xml;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks2012;Integrated
Security=SSPI";
public static int testParams()
{
SqlXmlParameter p;
XmlReader Reader;
XmlTextWriter tw;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandText = "select FirstName, LastName from Person.Person where LastName = ? For XML Auto";
p = cmd.CreateParameter();
p.Value = "Achong";
Reader = cmd.ExecuteXmlReader();
tw = new XmlTextWriter(Console.Out);
Reader.MoveToContent();
tw.WriteNode(Reader, false);
tw.Flush();
tw.Close();
Reader.Close();
return 0;
}
static int Main(string[] args)
{
testParams();
return 0;
}
}
To test the application
1. Make sure that you have the Microsoft .NET Framework installed on your computer.
2. Save the C# code (DocSample.cs) that is provided in this topic in a folder.
3. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
4. At the command prompt, execute DocSample.exe.
Executing Template Files by Using the
CommandStream Property
3/24/2017 • 1 min to read • Edit Online
This example illustrates how template files that consist of SQL or XPath queries can be specified by using the
CommandStream property of the SqlXmlCommand object. In this application, a FileStreamobject is opened for a
command file, and the file stream is assigned as the CommandStream that is executed.
In the following example, the CommandType property is specified as SqlXmlCommandType.Template (not as
TemplateFile).
This is the sample XML template:
<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:query>
SELECT TOP 2 ContactID, FirstName, LastName
FROM Person.Contact
FOR XML AUTO
</sql:query>
</ROOT>
This is the sample C# application. To test the application, save the template (TemplateFile.xml) and then execute the
application. The application executes the query that is specified in the XML template and displays the XML
document that is generated on the screen.
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
using System;
using Microsoft.Data.SqlXml;
using System.IO;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testParams()
{
//Stream strm;
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
ms.Position = 0;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandStream = new FileStream("TemplateFile.xml", FileMode.Open, FileAccess.Read);
cmd.CommandType = SqlXmlCommandType.Template;
using (Stream strm = cmd.ExecuteStream())
{
using (StreamReader sr = new StreamReader(strm)){
Console.WriteLine(sr.ReadToEnd());
}
}
return 0;
}
public static int Main(String[] args)
{
testParams();
return 0;
}
}
To test the application
1. Save the XML template (TemplateFile.xml) that is provided in this example in a folder.
2. Save the C# code (DocSample.cs) that is provided in this example in the same folder in which the schema is
stored. (If you store the files in a different folder, you will have to edit the code and specify the appropriate
directory path for the mapping schema.)
3. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
4. At the command prompt, execute DocSample.exe.
Executing Template Files by Using the CommandText
Property
3/24/2017 • 1 min to read • Edit Online
This example illustrates how template files that consist of SQL or XPath queries can be specified by using the
CommandTextproperty. Instead of specifying the SQL or XPath query as the value of CommandText, you can
specify a file name as the value. In the following example, the CommandType property is specified as
SqlXmlCommandType.TemplateFile.
The sample application executes this template:
<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:query>
SELECT TOP 2 ContactID, FirstName, LastName
FROM Person.Contact
FOR XML AUTO
</sql:query>
</ROOT>
This is the C# sample application. To test the application, save the template (TemplateFile.xml) and then execute the
application.
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
using
using
using
class
{
System;
Microsoft.Data.SqlXml;
System.IO;
Test
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testParams()
{
//Stream strm;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandType = SqlXmlCommandType.TemplateFile;
cmd.CommandText = "TemplateFile.xml";
using (Stream strm = cmd.ExecuteStream()){
using (StreamReader sr = new StreamReader(strm)){
Console.WriteLine(sr.ReadToEnd());
}
}
return 0;
}
public static int Main(String[] args)
{
testParams();
return 0;
}
}
To test the application
1. Make sure that you have the Microsoft .NET Framework installed on your computer.
2. Save the XML template (TemplateFile.xml) that is provided in this example in a folder.
3. Save the C# code (DocSample.cs) that is provided in this example in the same folder in which the schema is
stored. (If you store the files in a different folder, you will have to edit the code and specify the appropriate
directory path for the mapping schema.)
4. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
5. At the command prompt, execute DocSample.exe.
If you pass a parameter to a template, the parameter name must begin with at sign (@); for example,
p.Name="@ContactID", where p is a SqlXmlParameter object.
This is the updated template which takes one parameter.
<ROOT xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:header>
<sql:param name='ContactID'>1</sql:param>
</sql:header>
<sql:query>
SELECT ContactID, FirstName, LastName
FROM Person.Contact
WHERE ContactID=@ContactID
FOR XML AUTO
</sql:query>
</ROOT>
This is the updated code in which a parameter is passed in to execute the template.
public static int testParams()
{
Stream strm;
SqlXmlParameter p;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandType = SqlXmlCommandType.TemplateFile;
cmd.CommandText = "TemplateFile.xml";
p = cmd.CreateParameter();
p.Name="@ContactID";
p.Value = "1";
strm = cmd.ExecuteStream();
StreamReader sw = new StreamReader(strm);
Console.WriteLine(sw.ReadToEnd());
return 0;
}
Executing XPath Queries (SQLXML Managed Classes)
3/24/2017 • 1 min to read • Edit Online
This example illustrates how XPath queries are executed against a mapping schema.
Consider this schema:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="Con" sql:relation="Person.Contact" >
<xsd:complexType>
<xsd:sequence>
<xsd:element name="FName"
sql:field="FirstName"
type="xsd:string" />
<xsd:element name="LName"
sql:field="LastName"
type="xsd:string" />
</xsd:sequence>
<xsd:attribute name="ContactID" type="xsd:integer" />
</xsd:complexType>
</xsd:element>
</xsd:schema>
This C# application executes an XPath query against this schema (MySchema.xml).
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
using
using
using
class
{
System;
Microsoft.Data.SqlXml;
System.IO;
Test
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testXPath()
{
Stream strm;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.CommandText = "Con";
cmd.CommandType = SqlXmlCommandType.XPath;
cmd.RootTag = "ROOT";
cmd.SchemaPath = "MySchema.xml";
strm = cmd.ExecuteStream();
using (StreamReader sr = new StreamReader(strm)){
Console.WriteLine(sr.ReadToEnd());
}
return 0;
}
public static int Main(String[] args)
{
testXPath();
return 0;
}
}
To test the application
1. Make sure that you have the Microsoft .NET Framework installed on your computer.
2. Save the XSD schema (MySchema.xml) that is provided in this example in a folder.
3. Save the C# code (DocSample.cs) that is provided in this example in the same folder in which the schema is
stored. (If you store the files in a different folder, you will have to edit the code and specify the appropriate
directory path for the mapping schema.)
4. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
5. At the command prompt, execute DocSample.exe.
Executing XPath Queries with Namespaces (SQLXML
Managed Classes)
3/24/2017 • 2 min to read • Edit Online
XPath queries can include namespaces. If the schema elements are namespace-qualified (use a target namespace),
the XPath queries against the schema must specify the namespace.
Because the wildcard character (*) is not supported in Microsoft SQLXML 4.0, you must specify the XPath query by
using a namespace prefix. To resolve the prefix, use the namespaces property to specify the namespace binding.
In the following example, the XPath query specifies namespaces by using the wildcard character (*) and the localname() and namespace-uri() XPath functions. This XPath query returns all the elements where the local name is
Employee and the namespace URI is urn:myschema:Contacts:
/*[local-name() = 'Contact' and namespace-uri() = 'urn:myschema:Contacts']
In SQLXML 4.0, specify this XPath query with a namespace prefix. An example is x:Contact, where x is the
namespace prefix. Consider the following XSD schema:
<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>
Because this schema defines the target namespace, an XPath query (such as "Employee") against this schema must
include the namespace.
The following C# sample application executes an XPath query against the preceding XSD schema (MySchema.xml).
To resolve the prefix, specify the namespace binding by using the Namespaces property of the SqlXmlCommand
object.
NOTE
In the code, you must provide the name of the instance of SQL Server in the connection string.
using
using
using
class
{
System;
Microsoft.Data.SqlXml;
System.IO;
Test
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;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:Contacts'";
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;
}
}
To test this example, you must have the Microsoft .NET Framework installed on your computer.
To test the application
1. Save the XSD schema (MySchema.xml) that is provided in this example in a folder.
2. Save the C# code (DocSample.cs) that is provided in this example in the same folder in which the schema is
stored. (If you store the files in a different folder, you will have to edit the code and specify the appropriate
directory path for the mapping schema.)
3. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
4. At the command prompt, execute DocSample.exe.
Processing XML on the Client Side (SQLXML
Managed Classes)
3/24/2017 • 1 min to read • Edit Online
This example illustrates the use of the ClientSideXml property. The application executes a stored procedure on the
server. The result of the stored procedure (a two-column rowset) is processed on the client side to produce an XML
document.
The following GetContacts stored procedure returns FirstName and LastName of employees in the
Person.Contact table in the AdventureWorks database.
USE AdventureWorks
CREATE PROCEDURE GetContacts @LastName varchar(20)
AS
SELECT FirstName, LastName
FROM Person.Contact
WHERE LastName = @LastName
Go
This C# application executes the stored procedure and specifies the FOR XML AUTO option in specifying the
CommandText value. In the application, the ClientSideXml property of the SqlXmlCommand object is set to true.
This allows you to execute preexisting stored procedures that return a rowset and apply an XML transformation to
it on the client.
NOTE
In the code, you must provide the name of the instance of Microsoft SQL Server in the connection string.
using System;
using Microsoft.Data.SqlXml;
using System.IO;
class Test
{
static string ConnString = "Provider=SQLOLEDB;Server=(local);database=AdventureWorks;Integrated
Security=SSPI";
public static int testParams()
{
//Stream strm;
SqlXmlParameter p;
SqlXmlCommand cmd = new SqlXmlCommand(ConnString);
cmd.ClientSideXml = true;
cmd.CommandText = "EXEC GetContacts ? FOR XML NESTED";
p = cmd.CreateParameter();
p.Value = "Achong";
using (Stream strm = cmd.ExecuteStream())
{
using (StreamReader sr = new StreamReader(strm))
{
Console.WriteLine(sr.ReadToEnd());
}
}
return 0;
}
public static int Main(String[] args)
{
testParams();
return 0;
}
}
To test this example, you must have the Microsoft .NET Framework installed on your computer.
To test the application
1. Create the stored procedure.
2. Save the C# code (DocSample.cs) that is provided in this example in a folder. Edit the code to specify
appropriate login and password information.
3. Compile the code. To compile the code at the command prompt, use:
csc /reference:Microsoft.Data.SqlXML.dll DocSample.cs
This creates an executable (DocSample.exe).
4. At the command prompt, execute DocSample.exe.
SQLXML 4.0 .NET Framework Support - Managed
Classes
3/24/2017 • 1 min to read • Edit Online
Microsoft SQLXML 4.0 supports features that allow you to write applications to access XML data from an instance
of SQL Server, bring the data into the Microsoft .NET Framework environment, process the data, and send the
updates back to SQL Server.
Microsoft SQLXML Managed Classes exposes the functionality of SQLXML 4.0 inside the Microsoft .NET
Framework. With SQLXML Managed Classes, you can write a C# application to access XML data from an instance of
SQL Server, bring the data into the .NET Framework environment, process the data, and send the updates back to
SQL Server as a DiffGram to apply the updates. You must use a mapping schema when applying updates to a SQL
Server database using SQLXML Managed Classes. For a working sample, see Accessing SQLXML Functionality in
the .NET Environment.
To use the SQLXML Managed Classes with SQLXML 4.0, you must install Microsoft Visual Studio.
NOTE
The .NET Framework includes the SQL Server .NET Data Provider. This provider can be used to access SQL Server from the
.NET environment; however, it can handle only traditional SQL queries (that is, relational database queries with the exception
of FOR XML queries). You cannot execute XML templates or the server-side XPath queries in SQL Server.
For information about accessing and modifying data in SQL Server within the Microsoft .NET Framework, and
about using DiffGrams to update data in SQL Server tables, see Accessing SQLXML Functionality in the .NET
Environment.
NOTE
You can also write Microsoft Visual Studio applications to bulk load XML documents by using XML Bulk Load. For more
information, see Performing Bulk Load of XML Data (SQLXML 4.0). You must add a reference to the XML Bulk Load DLL
(Xblkld4.dll) in your application. This is a COM DLL for which Visual Studio .NET automatically creates the wrapper library.
This section provides sample applications that demonstrate how to use the Microsoft SQLXML Managed Classes:
Executing SQL Queries (SQLXML Managed Classes)
Executing SQL Queries by Using the ExecuteXMLReader Method
Processing XML on the Client Side (SQLXML Managed Classes)
Executing XPath Queries (SQLXML Managed Classes)
Executing XPath Queries with Namespaces (SQLXML Managed Classes)
Executing Template Files by Using the CommandText Property
Executing Template Files by Using the CommandStream Property
Applying an XSL Transformation (SQLXML Managed Classes)
SQLXML Managed Classes - SqlXmlAdapter Object
3/24/2017 • 1 min to read • Edit Online
This object provides methods that facilitate interaction with the dataset in the Microsoft .NET Framework. For a
working sample, see Accessing SQLXML Functionality in the .NET Environment.
The SqlXmlAdapter object supports these methods:
void Fill(DataSet ds)
Fills the dataset in the .NET Framework with the XML data retrieved from SQL Server.
void Update(DataSet ds)
Applies updates to records in SQL Server from the data in the dataset.
The SqlXmlAdapter object supports these constructors:
public SqlXmlAdapter(SqlXmlCommand cmd)
public SqlXmlAdapter(
string commandText,
SqlXmlCommandType cmdType,
string connectionString
)
public SqlXmlAdapter(
Stream commandStream,
SqlXmlCommandType cmdType,
string connectionString
)
See Also
SqlXmlCommand Object (SQLXML Managed Classes)
SqlXmlParameter Object (SQLXML Managed Classes)
SQLXML Managed Classes - SqlXmlCommand
Object
3/24/2017 • 4 min to read • Edit Online
This is the constructor for the SqlXmlCommand object:
public SqlXmlCommand(string cnString)
Where cnString is the ADO or OLEDB connection string that identifies the server, database, and the login
information—for example, Provider=SQLOLEDB; Server=(local); database=AdventureWorks; Integrated Security=SSPI"
.
In the connection string, the
provider string).
Provider
must be SQLOLEDB and the
Data Provider
should not be included in the
For a working sample, see Executing SQL Queries (SQLXML Managed Classes).
Methods
TheSqlXmlCommand object supports several methods, including the following methods for executing a command:
void ExecuteNonQuery()
Executes the command, but does not return anything. This method is useful if you want to execute a nonquery
command (that is, a command that does not return anything). An example is executing an updategram or a
DiffGram that updates records but returns nothing.
Stream ExecuteStream()
Returns a new Stream object. This method is useful when you want the query results returned to you in a new
stream. For a working sample, see Executing SQL Queries (SQLXML Managed Classes).
public void ExecuteToStream(Stream outputStream)
Writes the query results to an existing stream. This method is useful when you have a stream to which you need
the results appended (for example, to have the query results written to the
System.Web.HttpResponse.OutputStream). For a working sample, see Executing SQL Queries (SQLXML Managed
Classes).
XmlReader ExecuteXmlReader()
Returns an XmlReader object. You can use this method to either manipulate data in the XmlReader object directly
or plug in the chainable architecture of System.Xml. For more information, see the Microsoft .NET Framework
documentation. For a working sample, see Executing SQL Queries by Using the ExecuteXMLReader Method.
TheSqlXmlCommand object also supports these additional methods:
SqlXmlParameter CreateParameter()
Creates an SqlXmlParameter object. You can set values for the Name and Value parameters of this object. This
method is useful if you want to pass parameters to a command. For a working sample, see Executing SQL Queries
(SQLXML Managed Classes).
void ClearParameters()
Clears parameter(s) that were created for a given command object. This method is useful if you want to execute
multiple queries on the same command object.
Properties
The SqlXmlCommand object also supports these properties:
ClientSideXml
When set to True, specifies that conversion of the rowset to XML is to occur on the client instead of on the server.
This property is useful when you want to move the performance load to the middle tier. The property also allows
you to wrap the existing stored procedures with FOR XML to get XML output.
SchemaPath
The name of the mapping schema along with the directory path (for example, C:\x\y\MySchema.xml). This property
is useful for specifying a mapping schema for XPath queries. The path that is specified can be absolute or relative. If
the path is relative, the base path that is specified in Base Path is used to resolve the relative path. If no base path is
specified, the relative path is relative to the current directory. For a working sample, see Accessing SQLXML
Functionality in the .NET Environment.
XslPath
The name of the XSL file along with the directory path. The path that is specified can be absolute or relative. If the
path is relative, the base path that is specified in Base Path is used to resolve the relative path. If no base path is
specified, the relative path is relative to the current directory. For a working sample, see Applying an XSL
Transformation (SQLXML Managed Classes).
Base Path
The base path (a directory path). This property is useful for resolving a relative path that is specified for an XSL file
(by using the XslPath property), a mapping schema file (by using the SchemaPath property), or an external schema
reference in an XML template (specified by using the mapping-schema attribute).
OutputEncoding
Specifies the encoding for the stream that is returned when the command executes. This property is useful for
requesting a specific encoding for the stream that is returned. Some commonly used encodings are UTF-8, ANSI,
and Unicode. UTF-8 is the default encoding.
Namespaces
Enables the execution of XPath queries that use namespaces. For more information about XPath queries with
namespaces, see Executing XPath Queries with Namespaces (SQLXML Managed Classes). For a working sample,
see Executing XPath Queries (SQLXML Managed Classes).
RootTag
Provides the single root element for XML generated by command execution. A valid XML document requires a
single root-level tag. If the command executed generates an XML fragment (without a single top-level element) you
can specify a root element for the returning XML. For a working sample, see Applying an XSL Transformation
(SQLXML Managed Classes).
CommandText
The text of the command. This property is used for specifying the text of the command you want to execute. For a
working sample, see Executing SQL Queries (SQLXML Managed Classes).
CommandStream
The command stream. This property is useful if you want to execute a command from a file (for example, an XML
template). When you are using CommandStream, only "Template", "UpdateGram" and
"DiffGram"CommandType values are supported. For a working sample, see Executing Template Files by Using
the CommandStream Property.
CommandType
Identifies the type of command. This property is used for specifying the type of command you want to execute. The
values in the following table determine the type of the command. For a working sample, see Accessing SQLXML
Functionality in the .NET Environment.
VALUE
DESCRIPTION
SqlXmlCommandType.Sql
Executes an SQL command (for example,
SELECT * FROM Employees FOR XML AUTO
).
SqlXmlCommandType.XPath
Executes an XPath command (for example,
Employees[@EmployeeID=1] ).
SqlXmlCommandType.Template
Executes an XML template.
SqlXmlCommandType.TemplateFile
Executes a template file at the specified path.
SqlXmlCommandType.UpdateGram
Executes an updategram.
SqlXmlCommandType.Diffgram
Executes a DiffGram.
See Also
SqlXmlParameter Object (SQLXML Managed Classes)
SqlXmlAdapter Object (SQLXML Managed Classes)
SQLXML Managed Classes - SqlXmlParameter
Object
3/24/2017 • 1 min to read • Edit Online
The SqlXmlParameter object supports these properties:
Name
The name of the parameter. Commands can be passed parameters. Calling the CreateParameter method of the
SqlXmlCommand object creates the parameter object.
Value
The value of the parameter. For a working sample, see Executing SQL Queries (SQLXML Managed Classes).
See Also
SqlXmlCommand Object (SQLXML Managed Classes)
SqlXmlAdapter Object (SQLXML Managed Classes)
Accessing SQLXML Functionality in the .NET Environment