Pages

Showing posts with label DataSet. Show all posts
Showing posts with label DataSet. Show all posts

Wednesday, January 4, 2012

Converting a DataSet to XML node excluding Schema

In this blog post I'm going to explain you on how to return an object of type "DataSet" from a web service (SOAP) method.
 
In general when we return any type from a web method, it returns XML formatted string which then need to be parsed to get the resultant output. Whether it is a simple or any complex object type like Collections or generic list


However, when we returning a DataSet the resultant output will include table data along with the Schema.

So, if we need data with schema then it is well & good. 
What can we do to get only data and eliminate the schema from the DataSet?

The following code explains how we can achieve this:

DataSet ds = //... Use your logic to get DataSet from some DB/source
string xmlContent = ds.GetXml(); 
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.LoadXml(xmlContent);
System.Xml.XmlNode newNode = doc.DocumentElement;
return newNode;

GetXml method will return all the xml code in string variable for the corresponding DataSet (including schema).
Creating an XmlDocument object and load the Xml string using LoadXml method
Then we need to return DocumentElement of XmlDocument class to get only data excluding schema.

There is another technique to do the same with less effort, using Linq. Although, I never tried this to confirm..
//// When Using LINQ
//XElement newNode = XDocument.Parse(xmlContent).Root;

Try this and let me know if there are any other ways...

Monday, May 16, 2011

Optimized way to check if a dataset has any value

Working with datasets and we should make sure that object contains some data within.
Here is the optimized way to check if a dataset has any data within by using advanced .Net concepts like extension methods and Linq.

public static bool IsEmpty(this DataSet dataSet)
{
return dataSet == null || !(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any();
}

And we can use this extension method as follows:

DataSet dset = ... // Populate dataset by business method or logic
if (!dset.IsEmpty())
{
   ...
}

Extension methods provide a simple mechanism to extend types in the system (value, reference, and interface types) with new methods. These methods extend the original type and can be called like regular, defined instance methods, but they leave the original type and its methods untouched. Extension methods create the illusion that they are defined on a real type, but, in reality, no changes are made to the original types.

.NET Language-Integrated Query defines a set of general purpose standard query operators that allow traversal, filter, and projection operations to be expressed in a direct yet declarative way in any .NET-based programming language.