此示例代码主要示范了如何使用LINQ to XML的函数构造功能创建一个XML树。代码如下:

XElement Contacts = new XElement("Contacts",
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"),
        new XElement("Phone", "206-55-0144",
            new XAttribute("Type", "Home")),
        new XElement("Phone", "425-55-0145",
            new XAttribute("Type", "Work")),
        new XElement("Address",
            new XElement("Street", "123 Main St"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042"))));

Console.WriteLine(Contacts);

输出结果如下:

<Contacts>
  <Contact>
    <Name>Patrick Hines</Name>
    <Phone Type="Home">206-55-0144</Phone>
    <Phone Type="Work">425-55-0145</Phone>
    <Address>
      <Street>123 Main St</Street>
      <City>Mercer Island</City>
      <State>WA</State>
      <Postal>68042</Postal>
    </Address>
  </Contact>
</Contacts>