Read XML file in ASP.NET(C#)

This is very often when we face such situations to read XML file and create custom objects of it. There might be many articles in the internet but as I came across this thing recently, I thought of sharing my experience with people who might find it helpful.

Alright, in this article I will read a XML file from C#(ASP.NET) and create a custom object from it and then use it according to my need.



Here is the XML file, that is generated from an eCommerce site and has some product information.
<?xml version="1.0"?>
<Products>
  <Product>
    <ProductId>25303611</ProductId>
    <Barcode>171-H007/1</Barcode>
    <CategoryCode>548</CategoryCode>
    <Brand></Brand>
    <Image>https://img.epttavm.com/prodotti/592/025/303/25303611_0.jpg</Image>
    <Price>10.8227</Price>
    <ListPrice>10.8227</ListPrice>
    <BuyingPrice>10.8227</BuyingPrice>
    <TryPrice>10.8227</TryPrice>
    <TaxedPrice>10.8227</TaxedPrice>
    <EftPrice>10.8227</EftPrice>
    <SpecialPrice>10.8227</SpecialPrice>
    <Quantity>100</Quantity>
    <Variant1></Variant1>
    <Variant2></Variant2>
    <Variant3></Variant3>
    <Variant4></Variant4>
    <PriceDiff1></PriceDiff1>
    <PriceDiff2></PriceDiff2>
    <PriceDiff3></PriceDiff3>
    <PriceDiff4></PriceDiff4>
    <Manufacture></Manufacture>
    <TaxRate>8</TaxRate>
    <ModelNumber></ModelNumber>
    <Status>0</Status>
    <Attributes/>
    <CategoryPath>Ev Dekorasyon &gt;&gt; Banyo Tekstili test 1</CategoryPath>
    <GetTranslation></GetTranslation>
    <Culture>tr</Culture>
    <Name><![CDATA[Apolena Dekoratif Havlu Set 171-h007-1]]></Name>
    <Description><![CDATA[<p><font face="Arial"><strong>SIZES:</strong> Large 70 x 140 cm Towel+ Small Towel 50X 90 cm </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>FABRIC:</strong> 100% cotton </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Material information:</strong> 2-Piece decorative Towel. Specialized manufacture of our fabrics and soft. Products used in textile dyes that are Oeko-Tex® Standard 100 certification standards because it does not contain carcinogenic substances harmful to human and animal health. </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Care information:</strong> wash at 40 with water by hand or in a washing machine. Waiting and wet do not use bleach. During washing light and dark colors to keep separate. At low rpm you can dry in the dryer drum. </font></p>]]></Description>
  </Product>
  <Product>
    <ProductId>25303635</ProductId>
    <Barcode>171-H081/1</Barcode>
    <CategoryCode>548</CategoryCode>
    <Brand></Brand>
    <Image>https://img.epttavm.com/prodotti/592/025/303/25303635_0.jpg</Image>
    <Price>10.8227</Price>
    <ListPrice>10.8227</ListPrice>
    <BuyingPrice>10.8227</BuyingPrice>
    <TryPrice>10.8227</TryPrice>
    <TaxedPrice>10.8227</TaxedPrice>
    <EftPrice>10.8227</EftPrice>
    <SpecialPrice>10.8227</SpecialPrice>
    <Quantity>100</Quantity>
    <Variant1></Variant1>
    <Variant2></Variant2>
    <Variant3></Variant3>
    <Variant4></Variant4>
    <PriceDiff1></PriceDiff1>
    <PriceDiff2></PriceDiff2>
    <PriceDiff3></PriceDiff3>
    <PriceDiff4></PriceDiff4>
    <Manufacture></Manufacture>
    <TaxRate>8</TaxRate>
    <ModelNumber></ModelNumber>
    <Status>0</Status>
    <Attributes/>
    <CategoryPath>Ev Dekorasyon &gt;&gt; Banyo Tekstili</CategoryPath>
    <GetTranslation></GetTranslation>
    <Culture>tr</Culture>
    <Name><![CDATA[Apolena Dekoratif Havlu Set 171-h081-1]]></Name>
    <Description><![CDATA[<p><font face="Arial"><strong>SIZES:</strong> Large 70 x 140 cm Towel+ Small Towel 50X 90 cm </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>FABRIC:</strong> 100% cotton </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Material information:</strong> 2-Piece decorative Towel. Specialized manufacture of our fabrics and soft. Products used in textile dyes that are Oeko-Tex® Standard 100 certification standards because it does not contain carcinogenic substances harmful to human and animal health. </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Care information:</strong> wash at 40 with water by hand or in a washing machine. Waiting and wet do not use bleach. During washing light and dark colors to keep separate. At low rpm you can dry in the dryer drum. </font></p>]]></Description>
  </Product>
  <Product>
    <ProductId>25303647</ProductId>
    <Barcode>171-H060/1</Barcode>
    <CategoryCode>548</CategoryCode>
    <Brand></Brand>
    <Image>https://img.epttavm.com/prodotti/592/025/303/25303647_0.jpg</Image>
    <Price>10.8227</Price>
    <ListPrice>10.8227</ListPrice>
    <BuyingPrice>10.8227</BuyingPrice>
    <TryPrice>10.8227</TryPrice>
    <TaxedPrice>10.8227</TaxedPrice>
    <EftPrice>10.8227</EftPrice>
    <SpecialPrice>10.8227</SpecialPrice>
    <Quantity>100</Quantity>
    <Variant1></Variant1>
    <Variant2></Variant2>
    <Variant3></Variant3>
    <Variant4></Variant4>
    <PriceDiff1></PriceDiff1>
    <PriceDiff2></PriceDiff2>
    <PriceDiff3></PriceDiff3>
    <PriceDiff4></PriceDiff4>
    <Manufacture></Manufacture>
    <TaxRate>8</TaxRate>
    <ModelNumber></ModelNumber>
    <Status>0</Status>
    <Attributes/>
    <CategoryPath>Ev Dekorasyon &gt;&gt; Banyo Tekstili</CategoryPath>
    <GetTranslation></GetTranslation>
    <Culture>tr</Culture>
    <Name><![CDATA[Apolena Dekoratif Havlu Set 171-h060-1]]></Name>
    <Description><![CDATA[<p><font face="Arial"><strong>SIZES:</strong> Large 70 x 140 cm Towel+ Small Towel 50X 90 cm </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>FABRIC:</strong> 100% cotton </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Material information:</strong> 2-Piece decorative Towel. Specialized manufacture of our fabrics and soft. Products used in textile dyes that are Oeko-Tex® Standard 100 certification standards because it does not contain carcinogenic substances harmful to human and animal health. </font></p><p><font face="Arial"> </font></p><p><font face="Arial"><strong>Care information:</strong> wash at 40 with water by hand or in a washing machine. Waiting and wet do not use bleach. During washing light and dark colors to keep separate. At low rpm you can dry in the dryer drum. </font></p>]]></Description>
  </Product>
 <Products>
My Job is to extract the category and sub category details from that xml and save those to database for further usage.

I have created one class where I need the category and sub category to be stored. Below is the Category class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mpper.Entity
{
    public class Category
    {
        public int? Id { get; set; }

        public string Code { get; set; }

        public string Name { get; set; }

        public string SubCategoryName { get; set; }

        public string CategoryPath { get; set; }

        public int? ParentId { get; set; } 
    }
}



Now as the XML is having multiple nodes of products, I am expecting a list of Categories and here is how I get the data into the C# list from the XML file.
public List<Category> GenerateCategoryListFromProductFeedXML()
  {
      string path = System.Web.HttpContext.Current.Server.MapPath("~/Product Feed/product-feed.xml");

      XDocument xDoc = XDocument.Load(path);

      XElement xElement = XElement.Parse(xDoc.ToString());

      List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
      {
          Code = Convert.ToString(d.Element("CategoryCode").Value),
          CategoryPath = d.Element("CategoryPath").Value,
          Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
          SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
      }).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();

      return lstCategory;
  }
Here I am using the XDocument and XElement classes to parse the XML for which you need to add reference of "System.Xml.Linq" namespace in your project.

Now if you look into the above code you can see I am creating a XDocument object first, which will hold the XML data from the location. (I am using System.Web.HttpContext as my code was inside a class library. If you are going to use this method in a web project then you might not need that line to get the relative path).

Then XElement was responsible for parsing the string object we got from XDocument.



Once we parse the string xml data, we are ready to generate our custom C# object from the XElement. Here I am running a LINQ query on the xElement.Elements("Product"), where Product is the nested element inside the root element Products.

Then the LINQ code was simple enough, just create a new Category object and assign values from the XElement object to it.

That's it now return the List<Category> and do whatever you want to do with it.

Hope you like this article on how to read a XML file from C# and create a custom object from it.

Happy Codding....

No comments:

Post a Comment