Modify an XML Tree with LINQ - CSharp XML

CSharp examples for XML:XML LINQ

Description

Modify an XML Tree with LINQ

Demo Code


using System;// w  ww  .j av  a2s.  c  om
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class MainClass
    {
        static void Main(string[] args)
        {
            XElement rootElem = XElement.Load(@"ProductCatalog.xml");

            Console.WriteLine(rootElem);

            IEnumerable<XElement> prodElements
                = from elem in rootElem.Element("products").Elements()
                    where (elem.Name == "product")
                    select elem;

            foreach(XElement elem in prodElements)
            {
                int current_id = Int32.Parse((string)elem.Attribute("id"));
                elem.ReplaceAttributes(new XAttribute("id", current_id + 500));
            }

            Console.WriteLine(rootElem);

            IEnumerable<XElement> teaElements = from elem in rootElem.Element("products").Elements()
                    where (((string)elem.Element("description")).Contains("tea"))
                    select elem;

            foreach (XElement elem in teaElements)
            {
                elem.Remove();
            }

            Console.WriteLine(rootElem);

            // define and add a new element
            XElement newElement = new XElement("product",
                new XAttribute("id", 3000),
                new XElement("productName", "Car"),
                new XElement("description","description part"),
                new XElement("productPrice", 25.00),
                new XElement("inStock", true));

            rootElem.Element("products").Add(newElement);

            Console.WriteLine(rootElem);
        }
    }

Result


Related Tutorials