LINQ-Filter read XML


Features:
  1. Search on XML file
  2. Read Elements
  3. Read Sub Elements
  4. Read Attributes

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml;

using System.Xml.Linq;

 

namespace XMLUtility

{

    class Program

    {

        static void Main(string[] args)

        {

            ReadXml("UserDetail");

            Console.ReadKey();

        }

 

        private static void ReadXml(String ReportType)

        {

            string xmlFile = @"c:\ColumnMapping.xml";

            XElement reportTemplate = XElement.Load(xmlFile);

            IEnumerable<XElement> query = from rep in reportTemplate.Elements("Report")

                                          where (string)rep.Element("ReportType") == ReportType

                                          select rep;

            foreach (XElement rep in query)

            {

                Console.WriteLine(rep.Element("FileName").Value);

                foreach (XElement subRep in rep.Element("Columns").Elements())

                {

                    Console.WriteLine(subRep.Attribute("SourceFieldName").Value);

                }

 

            }

           

        }

    }

 

}

-----------------------------------------------------------------


XML File


<?xml version="1.0" standalone="yes" ?>
<Reports>
    <Report>
    <ReportType>UserDetail</ReportType>
    <FileName>myfile.xls</FileName>
    <SheetName>Users</SheetName>
    <Columns>
        <Column Type="General" SourceFieldName="FirstName" TargetFieldName="First Name" OledbType="VarChar" Value=""></Column>
        <Column Type="General" SourceFieldName="UserName" TargetFieldName="User Name" OledbType="VarChar" Value=""></Column>
        <Column Type="General" SourceFieldName="GmailID" TargetFieldName="Gmail Id" OledbType="VarChar" Value=""></Column>
       
    </Columns>
</Report>
<Report>
    <ReportType>RserDetail2</ReportType>
    <FileName>UserDetails.xls222</FileName>
    <SheetName>Users</SheetName>
    <Columns>
        <Column Type="General" SourceFieldName="FirstName" TargetFieldName="First Name" OledbType="VarChar" Value=""></Column>
        <Column Type="General" SourceFieldName="UserName" TargetFieldName="User Name" OledbType="VarChar" Value=""></Column>
        <Column Type="General" SourceFieldName="GmailID" TargetFieldName="Gmail Id" OledbType="VarChar" Value=""></Column>

    </Columns>
</Report>
</Reports>


The gadget spec URL could not be found

Comments