Showing posts with label xml. Show all posts
Showing posts with label xml. Show all posts

December 30, 2014

Load XML in a GridView using Asp.Net

Xml files can be loaded into a GridView control in asp.net. To load xml files, it can be usually binded to the GridView by creating the xml data source and then setting the data source property of the GridView. However, if xml files contains nodes, then it does not work and instead produces error -

The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.

To bind the xml file with nodes, it's easier to create a dataset and then to bind it to the gridview from code behind. Here is an example of how that would work.

Sample Xml File
  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Customers>
  3.   <Customer>
  4.     <Id>C1</Id>
  5.     <Name>John</Name>
  6.     <DateOfBirth>9 Jan 1960</DateOfBirth>
  7.     <Phone>99999999</Phone>
  8.     <Address>Canberra</Address>
  9.   </Customer>
  10.   <Customer>
  11.     <Id>C2</Id>
  12.     <Name>Smith</Name>
  13.     <DateOfBirth>10 August 1980</DateOfBirth>
  14.     <Phone>88888888</Phone>
  15.     <Address>Sydney</Address>
  16.   </Customer>
  17.   <Customer>
  18.     <Id>C3</Id>
  19.     <Name>Peter</Name>
  20.     <DateOfBirth>12 June 1978</DateOfBirth>
  21.     <Phone>77777777</Phone>
  22.     <Address>Melbourne</Address>
  23.   </Customer>
  24. </Customers>

 

aspx page
  1.     <div>
  2.     <asp:GridView ID="GridView1" runat="server">
  3.     </asp:GridView>
  4. </div>

 

Code to bind xml to gridview
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3.     if (!IsPostBack)
  4.     {
  5.         DataSet ds = new DataSet();
  6.         ds.ReadXml(MapPath("~/App_Data/data.xml"));
  7.         GridView1.DataSource = ds;
  8.         GridView1.DataBind();
  9.     }
  10. }

April 29, 2014

Convert between XDocument and XmlDocument

In one of the applications I was working, I noticed that as we have developed the application we have used both System.Xml and System.Xml.Linq namespaces. Now this can happen for a number of reasons including that as the application got developed, the new namespaces were used but the old code has not been refactored and it's not a priority as well as the latest .NET framework supports it. However, sometimes we might need to convert files from old to new version and vice versa. In my situation, I had to convert XDocument to XmlDocument and vice versa. To cater for this requirement I wrote a class with static methods that perform the conversion taking advantage of the XmlNodeReader and XmlReader classes.

Here's the sample code of the class.

XDoc to XmlDoc
  1. public class XmlConversion
  2. {
  3.     public static XmlDocument ToXmlDocument(XDocument xdoc)
  4.     {
  5.         var xmlDocument = new XmlDocument();
  6.         using (var reader = xdoc.CreateReader())
  7.         {
  8.             xmlDocument.Load(reader);
  9.         }
  10.         return xmlDocument;
  11.     }
  12.  
  13.     public static XDocument ToXDocument(XmlDocument xmlDoc)
  14.     {
  15.         using (var reader = new XmlNodeReader(xmlDoc))
  16.         {
  17.             reader.MoveToContent();
  18.             return XDocument.Load(reader);
  19.         }
  20.     }
  21. }

July 28, 2011

Transform object to xml using linq

Using Linq, it’s easily possible to query various types of data like sql database, xml, objects like DataTable, ArrayList. It’s also possible to transform data into other formats like xml using linq. In this article, I will demonstrate how to query an System.Collections.ArrayList collection and then to save the data in xml format.

At first, I will create an ArrayList object and add Person objects to it. The code to do is below.

Adding objects to ArrayList
  1. ArrayList list = new ArrayList();
  2. list.Add(new Person { FirstName = "Scooby", LastName = "Doo", DateOfBirth= new DateTime(2000, 12, 31), Height=160 });
  3. list.Add(new Person { FirstName = "Bugs", LastName = "Bunny", DateOfBirth = new DateTime(1999, 2, 7), Height = 170 });
  4. list.Add(new Person { FirstName = "Peter", LastName = "Pan", DateOfBirth = new DateTime(2001, 10, 31), Height = 150 });

The Person class has 4 public properties of different data types – string, DateTime and int as shown below.

Person class
  1. using System;
  2. namespace WebApplication1.CSClass
  3. {
  4.     public class Person
  5.     {
  6.         public string FirstName { get; set; }
  7.         public string LastName { get; set; }
  8.         public DateTime DateOfBirth { get; set; }
  9.         public int Height { get; set; }
  10.  
  11.         public override string ToString()
  12.         {
  13.             return FirstName + " " + LastName;
  14.         }
  15.     }
  16. }

Person objects are added to the ArrayList list which can be queried using linq as shown in my previous post on query ArrayList using Linq. While querying the list, System.Xml.Linq.XElement objects can be created which can be saved as xml using System.Xml.Linq.XDocument’s Save() method. The code to show this is below.

Transform ArrayList to xml
  1. private void TransformToXml()
  2. {
  3.     ArrayList list = new ArrayList();
  4.     list.Add(new Person { FirstName = "Scooby", LastName = "Doo", DateOfBirth= new DateTime(2000, 12, 31), Height=160 });
  5.     list.Add(new Person { FirstName = "Bugs", LastName = "Bunny", DateOfBirth = new DateTime(1999, 2, 7), Height = 170 });
  6.     list.Add(new Person { FirstName = "Peter", LastName = "Pan", DateOfBirth = new DateTime(2001, 10, 31), Height = 150 });
  7.  
  8.     var q = from Person p in list
  9.             orderby p.FirstName
  10.             orderby p.LastName
  11.             select p;
  12.  
  13.     var query = new XElement("Persons", from Person p in list
  14.                                 select new
  15.                                 XElement("Person",
  16.                                 new XElement("FirstName", p.FirstName),
  17.                                 new XElement("LastName", p.LastName),
  18.                                 new XElement("DateOfBirth", p.DateOfBirth),
  19.                                 new XElement("Height", p.Height)
  20.                                 )
  21.                                 );
  22.  
  23.     XDocument doc = new XDocument(query);
  24.     doc.Save(Server.MapPath("transform.xml"));
  25.  
  26.     var query2 = new XElement("Persons", from Person p in list
  27.                                 select new
  28.                                 XElement("Person",
  29.                                 new XAttribute("FirstName", p.FirstName),
  30.                                 new XAttribute("LastName", p.LastName),
  31.                                 new XAttribute("DateOfBirth", p.DateOfBirth),
  32.                                 new XAttribute("Height", p.Height)
  33.                                 )
  34.                                 );
  35.  
  36.     XDocument doc2 = new XDocument(query2);
  37.     doc2.Save(Server.MapPath("transform2.xml"));
  38. }

As can be seen, the ArrayList object is queried for Person objects. This is not really needed for the code to work but is an example on how objects can be queried from ArrayList.

Using another query, “query”, XElement objects are created. The names of the XElement – that is, the names of the xml elements are arbitrary and the value of the elements are obtained from the Person object. The XElement objects are then added to XDocument object and saved as xml using XDocument.Save() method. The resultant xml looks like below.

Xml from Linq to ArrayList
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Persons>
  3.   <Person>
  4.     <FirstName>Scooby</FirstName>
  5.     <LastName>Doo</LastName>
  6.     <DateOfBirth>2000-12-31T00:00:00</DateOfBirth>
  7.     <Height>160</Height>
  8.   </Person>
  9.   <Person>
  10.     <FirstName>Bugs</FirstName>
  11.     <LastName>Bunny</LastName>
  12.     <DateOfBirth>1999-02-07T00:00:00</DateOfBirth>
  13.     <Height>170</Height>
  14.   </Person>
  15.   <Person>
  16.     <FirstName>Peter</FirstName>
  17.     <LastName>Pan</LastName>
  18.     <DateOfBirth>2001-10-31T00:00:00</DateOfBirth>
  19.     <Height>150</Height>
  20.   </Person>
  21. </Persons>

One thing to note is that the xml declaration is automatically added. DateTime field – DateOfBirth is automatically converted to its string representation.

The xml produced previously contains elements only. The Linq query could be easily updated to change the data to be the attributes of xml elements. This is shown in another query – “query2”. System.Xml.Linq.XAttribute objects are created similarly instead of XElement objects and added to XElement object which is then added to XDocument object and saved as xml. The resultant xml file looks like below.

Xml from Linq to ArrayList
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <Persons>
  3.   <Person FirstName="Scooby" LastName="Doo" DateOfBirth="2000-12-31T00:00:00" Height="160" />
  4.   <Person FirstName="Bugs" LastName="Bunny" DateOfBirth="1999-02-07T00:00:00" Height="170" />
  5.   <Person FirstName="Peter" LastName="Pan" DateOfBirth="2001-10-31T00:00:00" Height="150" />
  6. </Persons>

The data looks similar to the previous xml except that they are now attributes of “Person” element instead of child elements.

June 27, 2011

Create XML using Linq to XML

Xml stands for eXtensible Markup Language that is designed to store and transfer data. An example xml file is below.

Sample Xml file
  1. <?xml version="1.0" encoding="utf-8" standalone="no"?>
  2. <!--demo on how to create xml file-->
  3. <root>
  4.   <Country id="1" name="Australia" capital="Canberra">
  5.     <state>New South Wales</state>
  6.     <state>Victoria</state>
  7.   </Country>
  8.   <Country id="2" name="India" capital="New Delhi">
  9.     <state>Maharashtra</state>
  10.     <state>Rajasthan</state>
  11.   </Country>
  12.   <Country id="2" name="Bangladesh" capital="Dhaka"><![CDATA[Bangladesh doesn't have any states.]]></Country>
  13. </root>

Xml file starts the xml declaration as in the first line. It supports comments similar to html comments as shown in line 2. It can have elements, can have attributes and can contain CData that is data that can be considered as plain text. Line 4 shows an example of element and attributes – Country is an element and id, name and capital are attributes. The value 1, Australia, etc are the values of the attributes.

In .NET, Linq to Xml makes it easy to create and parse xml documents. It’s easy to create xml, add declarations, add elements, attributes and also add data appropriately. The necessary classes are within the System.Xml.Linq namespace. Linq to Xml has XDocument class with xml documents can be created and loaded. XComment class can be used to add comments. XElement can be used to create elements and XAttribute classes can be used to add attributes to elements. XCData class can be used to add data in cdata format. An example on how to create xml using Linq to Xml is below.

Create xml using Linq
  1. private void CreateXml()
  2. {
  3.     XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "no"));
  4.  
  5.     XComment comment = new XComment("demo on how to create xml file");
  6.     doc.Add(comment);
  7.  
  8.     XElement el = new XElement("root");
  9.     XElement p1 = new XElement("Country", new object[] { new XAttribute("id", "1"), new XAttribute("name", "Australia"), new XAttribute("capital", "Canberra") });
  10.  
  11.     XElement p1city1 = new XElement("state", "New South Wales");
  12.     XElement p1city2 = new XElement("state", "Victoria");
  13.  
  14.     p1.Add(p1city1);
  15.     p1.Add(p1city2);
  16.  
  17.     XElement p2 = new XElement("Country", new object[] { new XAttribute("id", "2"), new XAttribute("name", "India"), new XAttribute("capital", "New Delhi") });
  18.  
  19.     XElement p2city1 = new XElement("state", "Maharashtra");
  20.     XElement p2city2 = new XElement("state", "Rajasthan");
  21.  
  22.     p2.Add(p2city1);
  23.     p2.Add(p2city2);
  24.  
  25.     XElement p3 = new XElement("Country", new object[] { new XAttribute("id", "3"), new XAttribute("name", "Bangladesh"), new XAttribute("capital", "Dhaka") });
  26.  
  27.     p3.Add(new XCData("Bangladesh doesn't have any states."));
  28.  
  29.     el.Add(p1);
  30.     el.Add(p2);
  31.     el.Add(p3);
  32.     doc.Add(el);
  33.  
  34.     doc.Save(Server.MapPath("country.xml"));            
  35. }

As can be seen, once the XElement, XComment, XAttribute objects are created, they got to be added to parent object. Once the necessary data has been added, the xml file can be saved using XDocument’s Save method as in line 34 above.

July 22, 2009

Create Xml using XmlDocument in asp.net

In this example, I will create a xml file using the XMLDocument class of the .NET framework. I will take advantage of the XmlElement, XMLAttribute and XmlComment classes.

At first, I will create a web page with a button control. The code for the page is below.

    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Get Xml" OnClick="GetXml" />
    </div>
    </form>


The Button control has a OnClick event handler that will create the xml file. Here is the code for the GetXml() method.

        protected void GetXml(object sender, EventArgs e)
        {
            XmlDocument doc = new XmlDocument();
       
            doc.AppendChild(doc.CreateXmlDeclaration("1.0", "utf-8", null));//create declaration

            XmlElement el = doc.CreateElement("root");//create root element
            doc.AppendChild(el);

            XmlElement child = doc.CreateElement("user");//create child element
            child.InnerText = "user1";                   //add text to element
            XmlAttribute att = doc.CreateAttribute("id");//create attribute
            att.Value = "1";                             //add value to attribute
            child.Attributes.Append(att);                //add attribute to element

            el.AppendChild(child);                       //add child element to root element
            el.AppendChild(doc.CreateComment("comment1"));//add comment

            child = doc.CreateElement("user");
            child.InnerText = "user2";

            att = doc.CreateAttribute("id");
            att.Value = "2";
            child.Attributes.Append(att);

            el.AppendChild(child);
            el.AppendChild(doc.CreateComment("comment2"));

            doc.AppendChild(el);
            
            doc.Save(Server.MapPath("~/App_Data/GetXml.xml"));// save xml file
        }


The method starts by creating a Xml-declaration using the CreateXmlDeclaration() method. Then, I am adding a root element using the XmlElement class, adding child elements using AppendChild() method and adding attributes using XmlAttributes objects to the elements. Finally, I am saving the file using the save() method of the XmlDocument() object.

Running this page and clicking the button produces the following xml file.

<?xml version="1.0" encoding="utf-8"?>
<root>
  <user id="1">user1</user>
  <!--comment1-->
  <user id="2">user2</user>
  <!--comment2-->
</root>


Reference: Shahed Kazi at AspNetify.com