Using LINQ to XML in combination with the Lists.asmx

Yesterday I was learning how to work with LINQ. I tried to use LINQ to XML to parse the XML that results from calling methods on the Lists.asmx.

I made a small windows application with Visual Studio 2008 to fill a combo box with lists. When you select a list, a grid view is populated with the some information of the fields of the selected list.

image

The combo box is populated as follows:

XmlNode listsResult = listService.GetListCollection();

// Get the Title and the ID from the xml
XDocument results = XDocument.Parse(listsResult.OuterXml);

var lists = from item in results.Descendants(XName.Get("List",         "http://schemas.microsoft.com/sharepoint/soap/"))
            select new
            {
                Title = item.Attribute("Title").Value,
                Id = item.Attribute("ID").Value
            };

ListsComboBox.DataSource = lists.ToList();
ListsComboBox.DisplayMember = "Title";
ListsComboBox.ValueMember = "Id";

The grid is populated as follows:

XmlNode result = listService.GetList(ListsComboBox.Text);
XDocument results = XDocument.Parse(result.OuterXml);

var fields = from item in results.Descendants(XName.Get("Field", "http://schemas.microsoft.com/sharepoint/soap/"))
             where item.Attribute("ID") != null
            select new
            {
                DisplayName = item.Attribute("DisplayName").Value,
                InternalName = item.Attribute("Name").Value,
                TypeAsString = item.Attribute("Type").Value,
                Id = item.Attribute("ID").Value ?? "empty"
            };

FieldsDataGridView.DataSource = fields.ToList();

What a delight not to have to parse all that XML again!