Create an XML file by using LINQ

The XML file is widely used in our development, it is very handy when our application needs to communicate with other application or service. LINQ syntax can be used to create an XML file in our practice.


Background

Data Source

Based on the above data, we have a Car class in our code.

public class Car
     {
         public int Year { get; set; }
         public string Manufacturer { get; set; }
         public string Name { get; set; }
         public double Displacement { get; set; }
         public int Cylinders { get; set; }
         public int City { get; set; }
         public int Highway { get; set; }
         public int Combined { get; set; }
}

In order to process the raw data in to Car objects, we need to implement a processing method and an extension method.

private static List ProcessCars(string path)
         {
             var query = File.ReadAllLines(path)            
                             .Skip(1)                 
                             .Where(l => l.Length > 1)    
                             .ToCar();         
             return query.ToList();     
         }

Extension Method

public static class CarExtensions
     {
         public static IEnumerable ToCar(this IEnumerable source)
         {
             foreach(var line in source)
             {
                 var columns = line.Split(',');
                 yield return new Car
                 {
                     Year = int.Parse(columns[0]),
                     Manufacturer = columns[1],
                     Name = columns[2],
                     Displacement = double.Parse(columns[3]),
                     Cylinders = int.Parse(columns[4]),
                     City = int.Parse(columns[5]),
                     Highway = int.Parse(columns[6]),
                     Combined = int.Parse(columns[7])
                 };
             }
         }
     }

Create an XML

private static void CreatXML()
   {
      var records = ProcessCars("fuel.csv");
      var document = new XDocument();         
      var cars = new XElement("Cars",             
                      from record in records              
                      select new XElement("Car",              
                             new XAttribute("Name", record.Name),                        
                             new XAttribute("Combine", record.Combined),                        
                             new XAttribute("Manufacturer", record.Manufacturer))             
                              );         
      document.Add(cars);         
      document.Save("fuel.xml");     
}

As we can see, we create an XML file by using the LINQ syntax. The hierarchy of implementation is demonstrated in the following diagram.

Run the Program

class Program
     {
         static void Main(string[] args)
         {
             CreatXML();
         }
}

We should be able to create an XML file if the program runs successfully. We can locate the XML file in our bin folder of the project solution.

The content of the file


Query the File

We can query an XML file by using LINQ syntax, too. Here is the code.

private static void QueryXML()
         {
             var document = XDocument.Load("fuel.xml");
             var query =
                        from element in document.Element("Cars").Elements("Car")
                        where element.Attribute("Manufacturer").Value == "BMW"
                        select element.Attribute("Name").Value;
             foreach(var name in query)         
             {             
                 Console.WriteLine(name);         
             }     
         }

As we can see, we dive into the element or attribute hierarchically, then we project each selected items.

Run the Program

class Program
     {
         static void Main(string[] args)
         {
             CreatXML();
             QueryXML();
         }
}

Output


448 Replies to “Create an XML file by using LINQ”

  1. Hello There. I found your blog using google. This is an extremely well written article.
    I’ll make sure to bookmark it and return to read more of your useful information. Thanks for the post.
    I’ll certainly return.

  2. I do nnot even know how I ended up here, but I thought this post was great.
    I don’t know who you are but certainly youu are going to a
    famous blogger if you are not alreaey 🙂 Cheers!

  3. Hi there to every body, it’s my first ppay a quick visit off this website;
    this blog contains aweskme and genuinely excellent data for visitors.

  4. Aw, this was a very nice post. In idea I wish to put in writing like this additionally – taking time and precise effort to make an excellent article… however what can I say… I procrastinate alot and not at all seem to get something done.

  5. Your style is so unique in comparison to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  6. Your style is very unique in comparison to other folks I have read stuff from. I appreciate you for posting when you have the opportunity, Guess I will just bookmark this page.

  7. Your style is so unique compared to other folks I’ve read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I’ll just book mark this web site.

  8. Your style is so unique in comparison to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  9. Your style is so unique compared to other folks I’ve read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I’ll just book mark this web site.

  10. Your style is really unique in comparison to other folks I’ve read stuff from. I appreciate you for posting when you’ve got the opportunity, Guess I’ll just book mark this web site.

  11. Your style is really unique in comparison to other folks I’ve read stuff from. I appreciate you for posting when you’ve got the opportunity, Guess I’ll just book mark this web site.

  12. Your style is so unique in comparison to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  13. Your style is so unique in comparison to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  14. Your style is really unique in comparison to other people I have read stuff from. Many thanks for posting when you have the opportunity, Guess I will just bookmark this web site.

  15. Your style is so unique in comparison to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  16. Your style is really unique compared to other people I’ve read stuff from. Many thanks for posting when you have the opportunity, Guess I will just bookmark this web site.

  17. Your style is unique compared to other folks I have read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I will just bookmark this page.

  18. Your style is so unique in comparison to other people I’ve read stuff from. Thank you for posting when you’ve got the opportunity, Guess I’ll just bookmark this web site.

  19. Your style is really unique in comparison to other people I have read stuff from. Many thanks for posting when you have the opportunity, Guess I will just bookmark this web site.

  20. You’re so awesome! I don’t suppose I’ve truly read something like this before. So great to discover another person with a few original thoughts on this issue. Really.. many thanks for starting this up. This site is something that is required on the web, someone with a bit of originality!

  21. TAKipçi SATIN AL
    Organik takipçi satın al işlemi ile instagram sayfalarınızı büyütebilirsiniz.
    Bunun için size sunulan instagram takipçi satın al
    seçeneklerini incelemenizi tavsiye ederiz. Seçenekler arasında Türk takipçi veya instagram düşmeyen takipçi satın al imkanı mevcuttur.

    Sayfanızı büyütebilmek için en iyi seçenek TAKipçi SATIN AL işlemidir.

  22. I do trust all of the ideas you have offered on your post.

    They’re very convincing and will definitely work.
    Nonetheless, the posts are too brief for starters.
    Could you please lengthen them a little from subsequent time?
    Thanks for the post.

  23. Every weekend i used to go to see this web page, for the reason that i want enjoyment,
    for the reason that this this web page conations genuinely pleasant funny stuff too.

  24. Nice post. I was checking continuously this blog and I am impressed!
    Very helpful information specifically the last part :
    ) I care for such information a lot. I was seeking this certain information for a long time.
    Thank you and best of luck.

  25. I look after a vape shop website directory and we have had a posting from a vape store in the USA that also offers CBD product lines. A Month later, PayPal has contacted use to say that our account has been limited and have requested us to take out PayPal as a payment solution from our vape shop web directory. We do not sell CBD items such as CBD oil. We only offer web marketing solutions to CBD companies. I have taken a look at Holland & Barrett– the UK’s Well known Health and wellness Store and if you take a close look, you will witness that they offer for sale a comparatively substantial range of CBD goods, primarily CBD oil and they also happen to accept PayPal as a settlement method. It emerges that PayPal is employing double standards to many different firms. As a result of this limitation, I can no longer accept PayPal on my CBD-related web site. This has limited my payment options and right now, I am greatly contingent on Cryptocurrency payments and direct bank transfers. I have spoken to a lawyer from a Magic Circle law office in The city of london and they explained that what PayPal is doing is entirely illegal and discriminatory as it ought to be applying an uniform criterion to all companies. I am yet to talk with a different attorney from a US law firm in The city of london to see what PayPal’s legal position is in the USA. In the meantime, I would be very appreciative if anyone here at targetdomain could offer me with alternative payment processors/merchants that work with CBD companies.

  26. My spouse and I stumbled over here different page and thought I might as well check things
    out. I like what I see so i am just following you.
    Look forward to looking into your web page yet again.

  27. Hi, I do believe this is an excellent blog. I stumbledupon it 😉
    I may come back yet again since i have bookmarked
    it. Money and freedom is the greatest way to change, may you be rich
    and continue to help others.

  28. I was wondering if you ever considered changing the structure of your website?
    Its very well written; I love what youve got to say. But maybe you could a little more in the
    way of content so people could connect with it better.
    Youve got an awful lot of text for only having one or two images.
    Maybe you could space it out better?

  29. Appreciating the dedication you put into your site and detailed information you offer.
    It’s great to come across a blog every once
    in a while that isn’t the same outdated rehashed material.
    Excellent read! I’ve bookmarked your site and I’m including your
    RSS feeds to my Google account.

  30. Leke Kremi Satışında Lider Firma hc.com.tr

    Cilt lekeleri, cilt tonu farklılıkları leke kremi gibi cildinizde oluşan herhangi
    bir leke için
    Hccare leke kremini deneyebilirsiniz iddalı bir marka olan bu firmanın tüm
    ürünleri güvenilir olduğu gibi leke kremi de güvenlidir.

    Leke kremi ; https://m2.tc/OZjV

  31. Thank you for another informative blog. The place
    else may just I get that kind of info written in such an ideal approach?
    I’ve a mission that I am simply now working on, and I have been on the glance
    out for such information.

  32. Hello, I think your website could possibly be having browser compatibility issues.
    Whenever I take a look at your web site in Safari, it
    looks fine however, if opening in IE, it has some
    overlapping issues. I simply wanted to give you a quick heads up!
    Apart from that, great site!

  33. I think this is one of the most important information for me.
    And i am glad reading your article. But wanna remark on few general things, The website
    style is great, the articles is really great : D.
    Good job, cheers

  34. It’s really a nice and useful piece of information. I’m satisfied
    that you simply shared this helpful info with us.
    Please stay us up to date like this. Thanks for sharing.

  35. The other day, while I was at work, my sister stole my iPad and tested to see if it can survive a forty foot drop,
    just so she can be a youtube sensation. My apple ipad is
    now broken and she has 83 views. I know this
    is entirely off topic but I had to share it with someone!

  36. Attractive part of content. I just stumbled upon your
    site and in accession capital to claim that I acquire in fact enjoyed account your weblog posts.

    Any way I’ll be subscribing for your augment or even I fulfillment you access
    persistently quickly.

  37. Everything is very open with a clear clarification of the issues.
    It was really informative. Your website is extremely helpful.
    Thanks for sharing!

  38. hey there and thanks in your info – I have definitely picked up something new from right here. I did then again experience a few technical points using this web site, since I experienced to reload the web site a lot of occasions previous to I may just get it to load correctly. I have been wondering in case your web hosting is OK? Not that I’m complaining, but slow loading cases occasions will sometimes affect your placement in google and can harm your quality ranking if advertising and ***********|advertising|advertising|advertising and *********** with Adwords. Anyway I’m adding this RSS to my e-mail and can look out for much extra of your respective exciting content. Make sure you update this again soon..

  39. I really like your blog.. very nice colors & theme.
    Did you make this website yourself or did you hire someone
    to do it for you? Plz respond as I’m looking to create
    my own blog and would like to find out where u
    got this from. many thanks

  40. Hi there, just became alert to your blog through Google, and found that it
    is truly informative. I am going to watch out for brussels.
    I’ll appreciate if you continue this in future. Many people will be
    benefited from your writing. Cheers!

  41. Hi there! This blog post couldn’t be written any better!
    Reading through this post reminds me of my previous roommate!
    He continually kept talking about this. I’ll forward this information to him.
    Pretty sure he’ll have a great read. Thank you
    for sharing!

  42. I’m truly enjoying the design and layout of your blog.
    It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a developer to create your theme?
    Exceptional work!

  43. What? s up it? s me, We are also visiting this website on a
    regular basis, this internet site is actually nice and the audiences are
    actually discussing good thoughts.

  44. This is genuinely interesting, You might be a very skilled blogger.
    I have became a member of your feed and even look forward to seeking more of your wonderful post.
    In addition, I? ve contributed your website in my social support systems!

    검증사이트

  45. This is actually interesting, You happen to be the very skilled doodlekit.
    I have joined up with your feed and even look forward to trying to find more of your own wonderful post.
    Furthermore, I? ve shared your website in my great example of such!

    먹튀사이트

  46. Heya we are for that major time here. My partner and i came across this kind of board and I to find It really helpful & it helped me out there much.
    I hope to offer the one thing again and support others such as you aided myself.

    먹튀보증업체

  47. Fantastic beat ! I would like to apprentice
    while you amend your web site, how can i subscribe for a blog
    web site? The account helped me a acceptable deal. I had been a little bit acquainted of
    this your broadcast provided bright clear concept

  48. Howdy! This is my first comment here so I just wanted to give
    a quick shout out and tell you I really enjoy reading through your posts.
    Can you recommend any other blogs/websites/forums that cover the
    same subjects? Many thanks!

  49. When I initially commented I seem to have clicked on the -Notify
    me when new comments are added- checkbox and now whenever a comment is added I
    get four emails with the exact same comment. Is there a way you can remove me from that service?
    Thanks a lot!

  50. Wonderful blog! Do you have any tips and hints for aspiring writers?
    I’m hoping to start my own website soon but I’m a little lost on everything.
    Would you propose starting with a free platform like WordPress or go for a paid option? There
    are so many choices out there that I’m completely confused ..

    Any ideas? Cheers!

  51. What i don’t understood is in truth how you are now not actually much more well-preferred than you may be now.
    You are very intelligent. You understand therefore significantly on the subject
    of this topic, produced me in my opinion imagine it from a lot of
    varied angles. Its like women and men aren’t interested unless it’s something to accomplish with Girl gaga!

    Your personal stuffs great. At all times deal with it up!

  52. You really make it seem so easy with your presentation but
    I find this matter to be really something that
    I think I would never understand. It seems too complex and very broad for me.
    I’m looking forward for your next post, I’ll try to
    get the hang of it!

Leave a Reply

Your email address will not be published. Required fields are marked *