Wednesday, November 19, 2008

Read XML using LINQ

Read XML using LINQ in ASP.NET

Here we have created a xml file containing a software various modules License Keys and reading the xml file according to settings using LINQ.


// Source sample

void WriteXML(string keyId)
{
try
{
//pick whatever filename with .xml extension
string filename = "c:\\License.xml";

XmlDocument xmlDoc = new XmlDocument();

try
{
xmlDoc.Load(filename);
}
catch (System.IO.FileNotFoundException)
{
//if file is not found, create a new xml file
XmlTextWriter xmlWriter = new XmlTextWriter(filename,
System.Text.Encoding.UTF8);
xmlWriter.Formatting = Formatting.Indented;
xmlWriter.WriteProcessingInstruction("xml",
"version='1.0' encoding='UTF-8'");
xmlWriter.WriteStartElement("RootMenu");
//If WriteProcessingInstruction is used as above,
//Do not use WriteEndElement() here
//xmlWriter.WriteEndElement();
//it will cause the to be
xmlWriter.Close();
xmlDoc.Load(filename);
}
XmlNode root = xmlDoc.DocumentElement;
XmlElement childNode = xmlDoc.CreateElement("Menus");
XmlElement childNode2 = xmlDoc.CreateElement("Menu");


root.AppendChild(childNode);

childNode.SetAttribute("name", plainText);
childNode.SetAttribute("KeyId", keyId);
childNode.AppendChild(childNode2);

childNode.SetAttribute("AccessValue",cipherText);

xmlDoc.Save(filename);
}
catch (Exception ex)
{
throw ex;
}
}




Here we are reading the xml file…

public bool LicenseKeyRight(string cipherText, string KeyID)//cipher text is the

//encrypted string
{
XDocument feedXML;
if (cipherText != String.Empty)
{

if (File.Exists(HttpContext.Current.Server.MapPath("License.xml")))
{
feedXML =
XDocument.Load(HttpContext.Current.Server.MapPath("License.xml"));
}

var feeds = from menu in feedXML.Descendants("Menu")
select new
{
Menus = menu.Parent.Attribute("name").Value,
AccessValue=
menu.Parent.Attribute("AccessValue").Value,
KeyId = menu.Parent.Attribute("KeyId").Value
};

string str = "";

foreach (var Property in feeds)
{
if (String.Compare(str, Property.Menus) != 0)
{
if ((String.Compare(Property.Menus, cipherText) == 0)
&& (String.Compare(KeyID, Property.KeyId)==0))
{

plainText= “”; // here we decrypt the encrypted
//string
if (String.Compare(plainText, cipherText) == 0)
{
return true;
}
}

}
str = Property.Menus;
}

}
return false;
}

No comments:

Post a Comment