Create a New XML Tree with LINQ - CSharp XML

CSharp examples for XML:XML LINQ

Description

Create a New XML Tree with LINQ

Demo Code


using System;/*from w  ww  .ja va  2 s . c  om*/
using System.Xml;
using System.Xml.Linq;

class MainClass
    {
        static void Main(string[] args)
        {

            XElement root = new XElement("products",
                new XElement("product",
                    new XAttribute("id", 1001),
                    new XElement("productName", "Car"),
                    new XElement("description",
                        "description part"),
                    new XElement("productPrice", 0.99),
                    new XElement("inStock", true)
                ));

            XElement teapot = new XElement("product");
            teapot.Add(new XAttribute("id", 1002));
            teapot.Add(new XElement("productName", "test test test"));
            teapot.Add(new XElement("description", "description test"));
            teapot.Add(new XElement("productPrice", 102.99));
            teapot.Add(new XElement("inStock", true));
            root.Add(teapot);

            XDocument doc = new XDocument(
                new XDeclaration("1.0", "", ""),
                root);

            doc.Save(Console.Out);
        }
    }

Result


Related Tutorials