Tuesday, August 21, 2012

Example for Reading & Writing XML File Using XElement

C# XElement
 XElement loads and parses XML. It allows you to remove lots of old code and eliminate the possibility of bugs and typos. Here we see an example of XElement from LINQ. We use it to load an XML document. We then query it using expressions in the C# language.
Here we look at how you can use the static Load method on an XML document with XElement. XElement and XDocument make using XML easy. To load an XML document into memory you only need one line of code.
Then: You can use methods on the XElement object to access the elements. 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace sampleTest
{
public partial class XElementExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Example();
}

public void Example()
{
XElement _x;
_x = XElement.Load(@"D:\myFile\myFile.xml");

try
{
// Get pages matching the title specified.
string t = "Alphanumeric Sorting in C#";
var v = (from page in _x.Elements("SitePage")
where t == page.Element("Title").Value
select page).ToList();


var k = (from page in _x.Elements("SitePage")
select page).ToList();

// Get category of first page matched.
string c = v.First().Element("Category").Value;

string d = k.First().Element("Category").Value;

// Count number of elements with that category element value.
int count = (from p in _x.Elements("SitePage")
where p.Element("Category").Value == c &&
p.Element("Visibility").Value == "Regular"
select p).Count();
}
catch (Exception ex)
{ }

}


}

}

XML
Here you can see the XML used for this article. You can match up the strings used in the above code samples with the tag and attribute names. This part of the article is completely application-specific, and your XML will be very different.
However:You can use some of the code samples in this article to help you deal with your XML.
File used [XML]

<?xml version="1.0"?>
<ArrayOfSitePage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <SitePage>
    <Visibility>Supplementary</Visibility>
    <Title>C# .NET Examples and Resources</Title>
    <Url></Url>
    <Category>None</Category>
  </SitePage>
  <SitePage>
    <Visibility>Supplementary</Visibility>
    <Title>Usability Guidelines for Web Writing</Title>
    <Url>Content/Usability-Writing.aspx</Url>
    <Category>None</Category>
  </SitePage>
  <SitePage>
    <Visibility>Regular</Visibility>
    <Title>Alphanumeric Sorting in C#</Title>
    <Url>Content/Alphanumeric-Sorting.aspx</Url>
    <Category>Algorithms</Category>
  </SitePage>
  <SitePage>
    <Visibility>Regular</Visibility>
    <Title>Word Count Algorithm in C#</Title>
    <Url>Content/Word-Count-Algorithm.aspx</Url>
    <Category>Algorithms</Category>
  </SitePage>
</ArrayOfSitePage>
Summary
We saw how you can use XElement and its Load method to quickly and effortlessly load XML. Load your XML file in a single statement and then run queries on it to generate output. Improvements could store more detailed data or be modified at runtime.
This below  article shows how to create an XML document using XLinq and later load it and loop through the elements of XML.


You must import following namespace:
using System.Xml.XLinq;
The XElement class represents an XML element in XLinq. The code creaes a root node called Authors and adds children Author nodes. The XAttribute class represents an attribute of an element.

XElement.Save method saves the contents of XElement to a XML file.

// Create a root node
            XElement authors = new XElement("Authors");
            // Add child nodes
            XAttribute name = new XAttribute("Author""Mahesh Chand");
            XElement book = new XElement("Book""GDI+ Programming");
            XElement cost = new XElement("Cost""$49.95");
            XElement publisher = new XElement("Publisher""Addison-Wesley");
            XElement author = new XElement("Author");
            author.Add(name);
            author.Add(book);
            author.Add(cost);
            author.Add(publisher);
            authors.Add(author);

            name = new XAttribute("Name""Mike Gold");
            book = new XElement("Book""Programmer's Guide to C#");
            cost = new XElement("Cost""$44.95");
            publisher = new XElement("Publisher""Microgold Publishing");
            author = new XElement("Author");
            author.Add(name);
            author.Add(book);
            author.Add(cost);
            author.Add(publisher);
            authors.Add(author);

            name = new XAttribute("Name""Scott Lysle");
            book = new XElement("Book""Custom Controls");
            cost = new XElement("Cost""$39.95");
            publisher = new XElement("Publisher""C# Corner");
            author = new XElement("Author");
            author.Add(name);
            author.Add(book);
            author.Add(cost);
            author.Add(publisher);
            authors.Add(author);          

            authors.Save(@"Authors.xml");
The output xml file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
- <Authors>
- <Author Author="Mahesh Chand">
  <Book>GDI+ Programming</Book>
  <Cost>$49.95</Cost>
  <Publisher>Addison-Wesley</Publisher>
  </Author>
- <Author Name="Mike Gold">
  <Book>Programmer's Guide to C#</Book>
  <Cost>$44.95</Cost>
  <Publisher>Microgold Publishing</Publisher>
  </Author>
- <Author Name="Scott Lysle">
  <Book>Custom Controls</Book>
  <Cost>$39.95</Cost>
  <Publisher>C# Corner</Publisher>
  </Author>
  </Authors>
The following code reads the Authors.xml file and loops through authors and displays the contents.
            XElement allData = XElement.Load("Authors.xml");
            
if (allData != null)
            {
                
IEnumerable<XElement> authors = allData.Descendants("Author");
                
foreach(XElement author in authors)
                    
Console.WriteLine((string)author);
            }