Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :
03/24/2008
Times viewed :
388
.NET SqlXmlCommand Class
The SqlXmlCommand class is your one-stop shop to access the XML features of
SQL Server and SQLXML. Similar to the System.Data.SqlClient.SqlCommand class or
the Command class in classic ADO, we can issue commands to the database and add
parameter values for parameterized queries. With the SqlXmlCommand class the
actual command can be in one of the five different SQLXML formats: SQL
statements returning XML, Updategrams, DiffGrams, XPath queries and Templates.
We tell the SqlXmlCommand object which one of the formats to execute by setting
the CommandType property to the corresponding value from the SqlXmlCommandType
enumeration before we execute the command.
We have two options to specify the command text: the CommandText or the
CommandStream property. The former is of type string, the latter of type
Stream. CommandText helps us to avoid any conversions or memory copies when we
dynamically create a SQL query or an XPath expression with a
System.Text.StringBuilder object or a call to the String.Format().
CommandStream on the other hand reads the command from Stream object, which
could be a FileStream to read from a file or a MemoryStream if we compose an
Updategram dynamically in memory.
Once we have set the command text and its type we can execute the command.
SqlXmlCommand gives us several options to retrieve the results. We can call the
ExecuteXmlReader() method to get all the results nicely packaged in an
XmlReader to traverse over the results. Alternatively, SQLXML will return the
results as a raw stream. If we call the ExecuteStream() method the
SqlXmlCommand will return a new stream and return it to us, or, if we want to
inject the results into an existing stream, we supply the target stream to the
ExecuteToStream() method. The next code example shows how we set up a
SqlXmlCommand to execute a SQL query returning XML and then write the results
directly to the Console with the ExecuteToStream() method.
SqlXmlCommand cmd = new SqlXmlCommand(connString);
cmd.Root = "Suppliers";
cmd.CommandType = SqlXmlCommandType.Sql;
cmd.CommandText = "SELECT SupplierName, WebSite FROM
Suppliers
FOR XML AUTO";
strm = cmd.ExecuteToStream( outStream );
outStream.Close();
}
The example above also sets the Root property to instruct the SqlXmlCommand
object to return well-formed XML. Without setting the Root property SQLXML
would return the XML fragment returned by SQL Server without a common root node,
which could cause exceptions if we processed the results with an XmlTextWriter
or an XmlDocument for example. Having the SqlXmlCommand generating the root tag
is not only convenient, it also avoids an extra, potentially expensive
processing step if we had to add a root element around the returned results.
The SqlXmlCommand class exposes more properties we haven’t discussed yet.
The SchemaPath property, for example, specifies the location of the mapping
schema for an XPath query or an Updategram which we will learn how to use
shortly. Another property allows us to handle the transformation of the
resultset into XML on the application server rather than using up
processing cycles on SQL Server. We will discuss client-side XML generation
later on. The SqlXmlCommand also does XSLT transformations as part of the
command execution, but we will not examine them closer because we should use
that feature only in a rather small application without well-defined
application layers. Mapping schemas are sufficient to handle the initial
transformation from the database schema into an XML format. The application
layer should handle more complex transformations to keep the data access layer
as generic as possible. Furthermore, the SqlXmlCommand class can only load XSL stylesheets
from the file system, whereas the System.Xml.Xslt namespace allows processing
of stylesheets from any type of stream source. Table 15.9 lists all methods and
properties for quick reference purposes.
1.9 The
SqlXmlCommand class executes the difference command types in SQLXML: SQL
Statements returning XML, XPath queries, Query Templates, Updategrams
andDiffgrams.
Constructor
SqlXmlCommand( string connectString )
Instantiates a new SqlXmlCommand from the specified connection string. The
connection string is in OLE DB format and must reference the SQLOLEDB
provider as in:
Provider=SQLOLEDB; Server=(local); database=Northwind; user
id=<UserLogin>; password=<UserPassword>.
Properties
public bool ClientSideXml { get; set; }
With the ClientSideXml property set to true SQLXML, not SQL Server,
handles the XML conversion of the query results. Converting the results
outside SQL Server helps to offload conversion load to the application
requesting the data. The property also allows you to wrap the existing stored
procedures with FOR XML to get XML output. Check 15.3.3.1 for more details.
public string SchemaPath { get; set; }
Sets the mapping schema to reference for execution of this command. The
path must be a local file system path or a UNC path, not a URL. It can be
absolute or relative. Relative paths are relative to the path specified by
the BasePath property or the executing process’ current directory if BasePath
is empty.
public string XslPath { get; set; }
Sets the XSLT stylesheet to apply to the results of the command. The path
must be a local file system path or a UNC path, not a URL. It can be absolute
or relative. Relative paths are relative to the path specified by the
BasePath property or the executing process’ current directory if BasePath is
empty.
public string BasePath { get; set; }
Sets the base path to resolve relative path references to schemas, XSLT
stylesheets or a schema reference inside a query template or an updategram.
public string OutputEncoding { get; set; }
Sets the encoding for the returned stream. The encoding name must be
recognized by SQLXML. The default is “UTF-8”. Other options are “ANSI” and
“Unicode”.
public string Namespaces { get; set; }
Defines prefix declarations namespaces to use in XPath queries. Multiple
declarations are separated by spaces.
public string RootTag { get; set; }
Sets the name of the root element for query results. If this properties is
empty the command will return the XML fragment returned by SQL Server,
regardless if it is well-formed XML.
public string CommandText { get; set; }
Sets the command text to execute. The command text can be any one of the
types in the SqlXmlCommandType enumeration. Set the CommandType property to
indicate the type.
public System.IO.Stream CommandStream { get; set; }
Passes a stream with the command text to execute. The stream can only
contain commands of type Template, UpdateGram and DiffGram.
public SqlXmlCommandType CommandType { get; set; }
Specifies the command type in the CommandText or CommandStream property,
which can be one of the following:
SqlXmlCommandType.Sql
SqlXmlCommandType.XPath
SqlXmlCommandType.Template
SqlXmlCommandType.TemplateFile
SqlXmlCommandType.UpdateGram
SqlXmlCommandType.Diffgram
The default is Sql.
Methods
public void ExecuteNonQuery()
Executes a command without returning any results.
public System.IO.Stream ExecuteStream()
Executes a command and returns the results in a stream..
public void ExecuteToStream(System.IO.Stream outputStream)
Executes a command and writes the results to the current position of the
passed in stream. For example you can write the output of several command
executions to the same stream.
public System.Xml.XmlReader ExecuteXmlReader()
Executes the command and returns an XmlReader to access the results.
public SqlXmlParameter CreateParameter()
Returns a SqlXmlParameter object that is automatically linked to the
command. You can set name and value of the parameter to execute parameterize
SQL statements or parameterized templates and updategrams.
public void ClearParameters()
Clears all parameters associated with the command.