Simple way to generate xml with LINQ in C#

Generate XML with LINQ.

I show you how you can create xml file in a readable and simple way by using LINQ.

At first I using the object XElement to create an xml document by properly adding elements to the generated file as in the example below.

Namespace – System.Xml.Linq.

XElement confirmOrder =
            new XElement("Batch",
                new XElement("Order",
                    new XElement("OrderHead",
                        new XElement("OrderCurrency",
                            new XElement("Currency", new XAttribute("Code", "PLN"))),
                    new XElement("OrderReferences", new XAttribute("xmlns", ""),
                        new XElement("BuyerNumber", "15")),
                    new XElement("Supplier", new XAttribute("xmlns", ""),
                        new XElement("Adress",
                            new XElement("Street", "Polna"),
                            new XElement("City", "Cracov"),
                            new XElement("PostCode", "32-412")),
                    new XElement("Buyer", new XAttribute("xmlns", ""),
                        new XElement("Address",
                            new XElement("Street", "Ulna"),
                            new XElement("City", "London"),
                            new XElement("PostCode", "11-222")),
                        new XElement("OrderLine", new XAttribute("xmlns", ""),
                            new XElement("Product",
                                new XElement("Name", "Pen"),
                            new XElement("Quantity", new XAttribute("Name", "szt."),
                                new XElement("Amount", "10")),
                            new XElement("Price",
                                new XElement("UnitPrice", "10,30")),
                            new XElement("BatchTrailer", new XAttribute("xmlns", ""),
                                new XElement("Checksum","10")))))))));

The object created in this way returns to us document xml which looks as fallows.



In this clear and simple way, we can create readable code for generate xml documents, of course, the XElement class offers a lot more for advanced specifics.


One Comment on “Simple way to generate xml with LINQ in C#”

  1. 1. Cały przykład jest oparty o Linq to Xml który należy do rodziny LINQ 😉
    2. Dla mnie struktura drzewa jest czytelna, łatwa i intuicyjna (widzę gdzie się kończy rekord/wiersz, a gdzie zaczyna) dla kogoś innego taka może nie być.

Leave a Reply

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