当前位置 > 首页 > Asp.net

LINQ to XML Quick Brain Dump

2009-8-26 5:53:00来源:Asp.net

LINQ to XML is a simple toolset that allows developers to easily interact with XML, whether it be in file form of on the wire in string form.

Write to an XML file

There are a few methods within the System.Xml.Linq namespace which make this interaction a breeze. The four main ones are:-

  • XDocument – Method which creates the XML document
  • XDeclaration – Allows you to set the declaration at the top of the file.
  • XElement – Creates a hierarchical element structure
  • XAttribute – Creates any attributes related to an element.

The following code shows a very simple way to generate an XML document for members of a club.

   1: Member[] members = new[] {
   2:  new Member{Age = 33, FullName = "John Havers", Title = "Mr"},
   3:  new Member{Age = 28, FullName = "Robin Southgate", Title = "Mrs"},
   4:  new Member{Age = 45, FullName = "Paul Chatwell", Title = "Mr"},
   5:     };
   6:  
   7: XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
   8:           new XElement("members",
   9:           from member in members
  10:           select new XElement("member",
  11:                  new XAttribute("age", member.Age),
  12:                  new XAttribute("title", member.Title),