Press "Enter" to skip to content

Using LINQ to XML to process SharePoint web service responses in Silverlight

Since working with LINQ to XML, I’ve totally fallen in love with it and could never go back to working with the XmlDocument objects.

Here are a few code snippets that can help you out. It is so simple once you get a hang of it.

GetListItems() – this Lists.asmx method returns the following response:

<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882"

xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"

xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema"

xmlns="http://schemas.microsoft.com/sharepoint/soap/">

<rs:data ItemCount="13">

   <z:row ... ows_ContentType="Task" ows_Title="New Task 1" ... />

   ... more rows here

</rs:data>

</listitems>

To get the value of the title into a List<string> object:

private List<string> ProcessListResults(SPListsWS.GetListItemsCompletedEventArgs e)

{

    string result = e.Result.ToString();

 

    XNamespace ns = "#RowsetSchema";

    XElement results = new XElement(e.Result);

 

    var listItems = from x in results.Descendants(ns + "row")

                    where x.Attribute("ows_Title") != null

                    select x;

 

    List<string> itemsList = new List<string>();

 

    foreach (var item in listItems)

    {

        string title = item.Attribute("ows_Title").Value;

        itemsList.Add(title);

    }

    return itemsList;

}

GetUserInfo() – this method is inside usergroup.asmx and gives us information regarding a user in an SPSite object. The response:

<GetUserInfo xmlns="http://schemas.microsoft.com/sharepoint/soap/directory/">

  <User ID="7" Sid="S-1-5-21-347908140-582334945-263120918-1111" Name="Radi"

    LoginName="DEV\radi" Email="" Notes="" IsSiteAdmin="False"

    IsDomainGroup="False" />

</GetUserInfo>

 

To get the LoginName:

public static string GetLoginFromServiceResponse(XElement result)

{

    XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/directory/";

 

    XName xUser = XName.Get("User", ns.NamespaceName);

    XName xUserInfo = XName.Get("GetUserInfo", ns.NamespaceName);

 

    XElement user = result.Element(xUser);

 

    if (user != null) {  return user.Attribute("LoginName").Value; }

 

    return null;

}

The passed in “result” is derived from e.Result.ToString().

Hope this helps!