Element and Attribute

The following code uses foreach loop to list elements.

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xml = @"<Root><client enabled='false'><timeout>60</timeout></client></Root>";

        XElement config = XElement.Parse(xml);
        foreach (XElement child in config.Elements())
            Console.WriteLine(child.Name);
    }
}

The output:


client

Get attribute out of element and change its value.

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xml = @"<Root><client enabled='false'></client></Root>";

        XElement config = XElement.Parse(xml);

        XElement client = config.Element("client");

        bool enabled = (bool)client.Attribute("enabled"); // Read attribute 
        Console.WriteLine(enabled); // True 
        client.Attribute("enabled").SetValue(!enabled); // Update attribute
    }
}

The output:


False

Add new element to XML with XElement

 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xml = @"<Root><client><timeout>60</timeout><retries>3</retries></client></Root>";

        XElement config = XElement.Parse(xml);
        XElement client = config.Element("client");
        int timeout = (int)client.Element("timeout"); // Read element 
        Console.WriteLine (timeout);  // 30 
        client.Element ("timeout").SetValue (timeout * 2);  // Update element

        client.Add(new XElement("retries", 3)); // Add new element

        Console.WriteLine(config);  // Implicitly call config.ToString()

    }
}

The output:

		60
		<Root><client><timeout>120</timeout><retries>3</retries><retries>3</retries></client></Root>
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.