segunda-feira, 22 de julho de 2013

XML, XSD and DataSet - How to read xml and transform into a dataset

Hi!

To transform XML into a DataSet is really simple.

Step 1


Create a XML.

<xml>
        <car>
            <brand>honda</brand>
        </car>
        <car>
            <brand>ford</brand>
        </car>
        <car>
            <brand>volkswagen</brand>
        </car>
        <car>
            <brand>toyota</brand>
        </car>
        <car>
            <brand>chevrolet</brand>
        </car>
</xml>

Step 2

Create the XSD

<?xml version="1.0" encoding="Windows-1252"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="xml">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="cars">
          <xs:complexType>
            <xs:sequence>
              <xs:element maxOccurs="unbounded" name="car">
                <xs:complexType>
                  <xs:sequence>
                    <xs:element name="brand" type="xs:string" />
                  </xs:sequence>
                </xs:complexType>
              </xs:element>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

How do I generate the XSD? If you are using Visual Studio, you're gonna find the following menu item



Step 3

Create a ConsoleApp project and use the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            DataSet lObjDataset = new DataSet();
            lObjDataset.ReadXmlSchema(@"C:\netdaniels\ConsoleApplication1\cars.xsd");
            lObjDataset.ReadXml(@"C:\netdaniels\ConsoleApplication1\cars.xml");

            Console.WriteLine("Table count:" + lObjDataset.Tables.Count.ToString());

            foreach (DataTable lObjDT in lObjDataset.Tables)
            {
               
                Console.WriteLine("Table name:" + lObjDT.TableName);

                foreach (DataColumn lObjDC in lObjDT.Columns)
                {
                    Console.WriteLine("Column name:" + lObjDC.ColumnName);
                }
            }
           
        }
    }
}

Et voilà! We're done!

The result is:


How simple is that?!

Há!!!



Nenhum comentário:

Postar um comentário