.NET FAQs Unleashed!
 
    
    

How to create attributes of an XML element tag, using XAttribute?

The XAttribute class is used to create an attribute object for an XML element. See the code example below:

 

using System;

using System.Collection.Generic;

using System.Xml.Linq;

 

namespace Build_Xml

{

  public class Student

  {

    public string name {get; set;}

    public string Id {get; set;}

  }

 

   public class Engine

   {

      static void main()

      {

          List<Student> students = CreateStudentList();

         

          var studentXml = new XDocument(); 

          var rootElem = new XEleemnt(“Students”);

          studentXml.Add(rootElem);

          foreach(Student student in students)

          {

                // Create an element for the Student object

var studentElem = new XElement(“Student”);

 

// Add an attribute for the name property

var nameAttr = new XAttribute(“name”);

studentElem.Add(nameAttr);

 

// Add an attribute for the Id property

var IdAttr = new XAttribute(“Id”);

studentElem.Add(IdAttr);

 

rootElem.Add(studentElem);

      }

      Console.WriteLine(studentXml.ToString());

     Console.Read();

  }

 

private static List<Student> CreateStudentList()

      {

new Student {name=”Elena”,Id=”405”},

new Student {name=”John”,Id=”406”}     

      };

      Return students;

   }

}

 

The code above will output the following XML document:

 

<Students>

  <Student name=”Elena” Id=”405”>

  </Student>

  <Student name=”John” Id=”406”>

  </Student>

</Students>

Silverlight DOM Parser   Parents of Child Elements   XML document using LINQ   XML document using XDocument and XElement?   Attributes and XAttribute    Read XML using XPathDocument    Search XML using LINQ   Serialize and deserialize XML    Empty XML element   Advantage of XmlReader and XmlWriter   Well formed XML VS Valid XML    XHTML VS HTML   Define XML  

More Interview Questions.....