Wednesday, March 28, 2012

Read xml from sql server column(xml data type) and return as XmlDocument in C#

Hi Everyone:

I would appreciate it if someone can help me this problem as I am a c# beginner. I am writing a C# method that is supposed to read in XML from SQL Server 2005 Database. The table I am reading from has a column which is set to XML data type and has a well formed XML document. I would like to load that xml into a xml document in my c# and return back as a xmldocument in my method. Here is my method so far, as you can see i am utilizing the Enterprise Library Data Access Block for db access. I woud appreciate if you can provide me with some help. Thanks.

Note: What i am doing right now maybe completely off track from what I am trying to achieve. here is the code I have so far:

private const string SQLGETCNFS = "SELECT EntityDefinitionXML FROM EntityDefinition WHERE EntityID = ";

/// <summary>
/// Method retrieves XML Entity Definition from the configuration database
/// </summary>
/// <param name="entityID"></param>
/// <returns>XmlDocument Type</returns>
public XmlDocument GetCustomerCNSFData(string entityID)
{
//connect to config database
Database db = DatabaseFactory.CreateDatabase();
string sqlCommand = SQLGETCNFS + entityID.ToString();

IDataReader reader = db.ExecuteReader(CommandType.Text, sqlCommand);


while (reader.Read())
{
SqlXml sx = reader.GetSqlXml(1);
XmlReader xr = sx.CreateReader();
xr.Read();
}
return null;
}

You can create a new instance of XmlDocument and then call the Load method and pass the XmlReader that you created from SqlXml.

Regards,

Galex Yen

No comments:

Post a Comment