Tuesday, May 06, 2008

Read Write and Search XML Document in ASP.NET

You often need to read, write or search some phrase in an XML document and you can use XmlDocument or any class among a lot present in .NET framework but what
if you wish to bind your business objects
the list of business objects to the XmlDocument.

You can use the code below to do this.

What you need to do for this is to keep the name of properties of your business objects same as the name of attributes are present in the XML file you wanna load.

This class make use of XmlReader and XmlWriter base classes provided by .NET framework.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;
using System.IO;

///
/// XMLDataHelper provides way to access nodes and bind them directly to custom objects.
/// Also Save XMLFragment at the end of the Xml File
///

public class XMLDataHelper : IDisposable
{
#region Variables

private static string _baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
private static string _documentDirectory = _baseDirectory + "App_Data/";

protected string _query;
protected XmlReader xmlReader;
protected XmlWriter xmlWriter;
#endregion

#region constructors
public XMLDataHelper()
{
string xmlFile = ConfigurationManager.AppSettings["XmlFileName"].ToString();
xmlReader = XmlReader.Create(xmlFile);
}

public XMLDataHelper(string xmlFile)
{
xmlReader = XmlReader.Create(xmlFile);
}
public XMLDataHelper(string xmlFile, string xmlFileForWriter)
{
xmlReader = XmlReader.Create(xmlFile);
xmlWriter = XmlWriter.Create(xmlFileForWriter);

}
#endregion

#region Load Object
public T LoadObject(string nodeName, Dictionary attrFieldsLookUp) where T : new()
{
T obj = new T();
if (string.IsNullOrEmpty(nodeName))
{
throw new Exception("Node not specified.");
}
bool IsRequestedItem = true;
PropertyInfo[] objPropInfo = obj.GetType().GetProperties();
while (xmlReader.ReadToFollowing(nodeName))
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.NodeType != XmlNodeType.Document)
{
XmlReader nodeXmlReader = xmlReader.ReadSubtree();
while (nodeXmlReader.Read())
{
IsRequestedItem = false;
foreach (string key in attrFieldsLookUp.Keys)
{
if (attrFieldsLookUp[key.ToUpper()] == nodeXmlReader.GetAttribute(key))
{
IsRequestedItem = true;
}
else
{
IsRequestedItem = false;
break;
}
}
if (IsRequestedItem)
{
GetObjectFromReaderNode(ref obj, ref nodeXmlReader, ref objPropInfo, true, nodeName);
}
}
}
}
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
}
return obj;
}
#endregion

#region GetObjectFromReaderNode
private void GetObjectFromReaderNode(ref T obj, ref XmlReader nodeXmlReader, ref PropertyInfo[] objPropInfo, bool AreElementsReq, string nodeName)
{
Dictionary xmlFileValues = new Dictionary();
while (nodeXmlReader.MoveToNextAttribute())
{
xmlFileValues.Add(nodeXmlReader.Name.ToUpper(), nodeXmlReader.Value);
}
foreach (PropertyInfo pi in objPropInfo)
{
if (pi.Name == "DEPTH")
{
pi.SetValue(obj, (object)(nodeXmlReader.Depth + 1), null);
}
else
{
string currAttrVal;
if (xmlFileValues.TryGetValue(pi.Name.ToUpper(), out currAttrVal))
{
if (pi.PropertyType == typeof(Boolean))
{
pi.SetValue(obj, Convert.ToBoolean(currAttrVal.ToLower()), null);
}
else
{
pi.SetValue(obj, (object)currAttrVal, null);
}
}
}
}
if (AreElementsReq)
{
bool firstOccur = true;
while (xmlReader.Read() && firstOccur)
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.NodeType != XmlNodeType.Document)
{
string elementName = nodeXmlReader.Name;
// To Stop Retrieving Inner Elements value
if (elementName == nodeName)
{
firstOccur = false;
}
string currElementVal;
foreach (PropertyInfo pi in objPropInfo)
{
if (pi.Name.ToUpper() == elementName.ToUpper())
{
pi.SetValue(obj, (object)nodeXmlReader.ReadElementString(), null);
}
}
}
}
}
}
#endregion

#region LoadList
public List LoadList(string nodeName, bool includeElement) where T : new()
{
T obj = new T();
List retList = new List();
if (string.IsNullOrEmpty(nodeName))
{
throw new Exception("Node not specified.");
}
bool IsRequestedItem = true;
PropertyInfo[] objPropInfo = obj.GetType().GetProperties();
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.NodeType != XmlNodeType.Document)
{
if (xmlReader.Name == nodeName)
{
obj = new T();
GetObjectFromReaderNode(ref obj, ref xmlReader, ref objPropInfo, includeElement, nodeName);
retList.Add(obj);
}
}
}
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
}
return retList;
}
#endregion

#region SaveXmlFragment
// Summary:
// To Save XmlFragment at the end of the file
public void SaveXmlFragment(string rawXmlFragment, string rootItem)
{
try
{
using (xmlReader)
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == rootItem)
{
xmlWriter.WriteStartElement(rootItem);
xmlWriter.WriteRaw(xmlReader.ReadInnerXml());
xmlWriter.WriteRaw(rawXmlFragment);
xmlWriter.WriteEndElement();
}
else if (xmlReader.NodeType == XmlNodeType.Comment || xmlReader.NodeType == XmlNodeType.Text || xmlReader.NodeType == XmlNodeType.Whitespace)
{

}
else
{
xmlWriter.WriteNode(xmlReader, true);
}
}
xmlWriter.Flush();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
xmlReader.Close();
xmlWriter.Close();
FileInfo fi = new FileInfo(_documentDirectory + "SiteData.xml");
File.Copy(_documentDirectory + "_tempSiteData.xml", fi.FullName, true);
}
}
#endregion

#region Search Document
// Summary:
// To Save XmlFragment at the end of the file
public SortedDictionary> SearchDocument(string searchText, string nodeName, string propertyNameToLookFor) where T : new()
{
List searchWords = new List();

string[] allWords = searchText.Split(' ');

for (int i = 0; i <>> retDictionary = new SortedDictionary>();

T obj = new T();

PropertyInfo[] piAll = obj.GetType().GetProperties();

List retList = this.LoadList(nodeName, true);

foreach (T item in retList)
{
string content = "";
int relevance = 0;
foreach (PropertyInfo pi in piAll)
{
if (pi.Name == propertyNameToLookFor)
{
content = Convert.ToString(pi.GetValue(item, null));
}
}
string[] contentSplitted = content.Split(' ');
foreach (string word in searchWords)
{
for (int i = 0; i <> relCorrList = new List();
relCorrList.Add(item);
retDictionary.Add(relevance, relCorrList);
}
else
{
retDictionary[relevance].Add(item);
}
}
}
return retDictionary;
}
#endregion

#region IDisposable Members
public void Dispose()
{
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
xmlWriter.Close();
}
}

#endregion


}

if you are getting it difficult to understand or have some queries you can put a reply or mail me at
shashank.abes at gmail.com

No comments:

Post a Comment