CSharp - Creating Elements with XElement

Introduction

XElement has several constructors, but we are going to examine two of them:

XElement.XElement(XName name, object content);
XElement.XElement(XName name, params object[] content);

The first constructor creates an element from a text value without child nodes.

The following code creates an Element Using the first constructor.

Demo

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

class Program//from   www.  java 2 s  .co m
{
    static void Main(string[] args){
           XElement firstName = new XElement("FirstName", "Joe");
       Console.WriteLine((string)firstName);
    }
}

Result

The first argument of the constructor is an XName object.

An XName object will be created by implicitly converting the input string to an XName.

The second argument is a single object representing the element's content.

API will convert that string literal of "Joe" to an XText object on the fly.

In the output statement, Console.WriteLine((string)firstName);, we are casting the element to the type of its value, which is a string.

The second XElement constructor can accept multiple objects for the content.

Related Topics