WEB开发网
开发学院数据库MSSQL Server 从 SQL Server 2005 中处理 XML 阅读

从 SQL Server 2005 中处理 XML

 2007-05-13 09:26:22 来源:WEB开发网   
核心提示: using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using System.Xml;using System.Xml.Schema;void GetSchemaSet
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Xml;
using System.Xml.Schema;
void GetSchemaSet {
// get a connection string from a config file
string s = GetConnectStringFromConfigFile("xmldb");
using (SqlConnection conn = new SqlConnection(s))
using (SqlCommand cmd = new SqlCommand(
    "SELECT xml_schema_namespace(N'dbo',N'books_xsd')", conn))
{
 XMLSCHEMASet ss = new XMLSCHEMASet();
 conn.Open();
 SqlDataReader rdr = cmd.ExecuteReader();
 rdr.Read();
 XmlReader xr = rdr.GetSqlXml(0).CreateReader();
 do
 {
  ss.Add(XMLSCHEMA.Read(xr, null));
  xr.Read();
 }
 while (xr.NodeType == XmlNodeType.Element);
}
}

如果手边有 XMLSCHEMASet,我们就可以将客户端 XML 验证代码集成到 Add 例程中。您瞧!这就是客户端验证。

void ValidateAndStore(XMLSCHEMASet ss)
{
 // associate the XMLSCHEMASet with the XmlReader
 XmlReaderSettings settings = new XmlReaderSettings();
 settings.Schemas = ss;
 string s = GetConnectStringFromConfigFile("xmldb");
 using (XmlReader xr = XmlReader.Create(
  "file://c:/temp/somefile.xml", settings))
 // get a connection string from a config file
 using (SqlConnection conn = new SqlConnection(s))
 using (SqlCommand cmd = new SqlCommand(
  "insert typed_xml values(@x)", conn))
 {
  try
  {
   conn.Open();
   // should throw an exception here if not schema valid
   cmd.Parameters.AddWithValue("@x", new SqlXml(xr));
   int i = cmd.ExecuteNonQuery();
  }
  catch (Exception e)
  {
    Console.WriteLine(e.Message);
  }
 }
}

尽管不是每个应用程序都需要客户端 XML 架构验证,但是当应用程序需要它时知道它是可用的会令人非常兴奋。当您在如下 SELECT...FOR XML 语句上使用新的 SQL Server 2005 XMLSCHEMA 选项时,也产生 XML 架构:

上一页  5 6 7 8 9 10 

Tags:SQL Server 处理

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接