Using LINQ to parse XML data coming back from SharePoint web services

Quick example of using one of the many built-in SharePoint web services to populate a WPF control. 

In this particular instance I am connecting to the SharePoint lists web service Lists.asmx to retrieve data from the list and bind to a WPF listbox control. 
Should be easily ported over to a SharePoint web part or ASPNET web page etc.   No warranties:)

 

private ObservableCollection<Notification> notifications;
        public void getData()
        {

//hardcoding the list name as the ID for the web service call-feel free to do something more creative:)           

string listId = "Notifications";
            XNamespace s = "http://schemas.microsoft.com/sharepoint/soap/";
            XNamespace rs = "urn:schemas-microsoft-com:rowset";
            XNamespace z = "#RowsetSchema";

            string userDisplayName = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Replace(‘\\’, ‘,’);
            string[] userFriendlyNameArr = userDisplayName.Split(‘,’);
            userDisplayName = userFriendlyNameArr[1].ToString();

            lists.Lists ws = new lists.Lists();
            ws.UseDefaultCredentials = true;

            ws.Url = "http://[server]/[site]/_vti_bin/Lists.asmx";
            XElement queryOptions = new XElement("QueryOptions",

               new XElement("IncludeMandatoryColumns", false)

            );

            XElement viewFields = new XElement("ViewFields",

            new XElement("FieldRef", new XAttribute("Name", "ActorName")),

            new XElement("FieldRef", new XAttribute("Name", "ItemTitle")),

            new XElement("FieldRef", new XAttribute("Name", "ItemURL")),

            new XElement("FieldRef", new XAttribute("Name", "ListTitle")),

            new XElement("FieldRef", new XAttribute("Name", "EventTime")),

            new XElement("FieldRef", new XAttribute("Name", "ListType")),

            new XElement("FieldRef", new XAttribute("Name", "ItemType")),

            new XElement("FieldRef", new XAttribute("Name", "ListUrl")),

            new XElement("FieldRef", new XAttribute("Name", "ActorID")),

            new XElement("FieldRef", new XAttribute("Name", "Action"))

            );

           XElement notifications = new XElement("Notifications",

                                   ws.GetListItems((string)listId, "" , null,

                                    viewFields.GetXmlNode(), "", queryOptions.GetXmlNode(), "")

                                     .GetXElement()

                                     .Descendants(z + "row")

                                     .Select(r =>

                                         new XElement("row",

                                             r.Attribute("ows_ActorName"),

                                             r.Attribute("ows_ActorID"),

                                             r.Attribute("ows_Action"),
                                             r.Attribute("ows_ItemTitle"),
                                             r.Attribute("ows_ItemType"),
                                             r.Attribute("ows_ItemURL"),

                                             r.Attribute("ows_ListTitle"),

                                             r.Attribute("ows_ListUrl"),

                                             r.Attribute("ows_EventTime"),

                                             r.Attribute("ows_ListType")

                                         )

                                    )

                            );

            ProcessResponse(notifications.ToStringAlignAttributes());

        }

        private void ProcessResponse(string response)
        {
           

//using my own custom list in SharePoint as the source-custom fields and all so make sure to use whatever fields are appropriate for your case

XDocument results = XDocument.Parse(response);

            var items = from item in results.Descendants("row")
                        where item.Attribute("ows_ItemTitle") != null
                        orderby (DateTime)item.Attribute("ows_EventTime") descending
                        select new Notification
                        {
                            ActorName = (string)item.Attribute("ows_ActorName"),
                            ActorId = (int)item.Attribute("ows_ActorID"),
                            Action = (string)item.Attribute("ows_Action"),
                            ItemTitle = (string)item.Attribute("ows_ItemTitle"),
                            ItemType = (string)item.Attribute("ows_ItemType"),
                            ItemUrl = (string)item.Attribute("ows_ItemURL"),
                            ListTitle = (string)item.Attribute("ows_ListTitle"),
                            ListUrl = (string)item.Attribute("ows_ListUrl"),
                            EventTime = (DateTime)item.Attribute("ows_EventTime"),
                            ListType = (string)item.Attribute("ows_ListType"),
                            ActivitiesText = (string)item.Attribute("ows_ActorName") + " " + (string)item.Attribute("ows_Action") + " " + (string)item.Attribute("ows_ItemTitle") + " " + "into" + " " + (string)item.Attribute("ows_ListType") + " " + "named " + (string)item.Attribute("ows_ListTitle"),

                        };

            ActivitiesListView.ItemsSource = items;
        }

 

//Extension methods credit to Eric White Technical Evangelist for Open XML for these.

public static class MyExtensions
    {

       

public static XElement GetXElement(this XmlNode node)
        {

            XDocument xDoc = new XDocument();

            using (XmlWriter xmlWriter = xDoc.CreateWriter())

                node.WriteTo(xmlWriter);

            return xDoc.Root;

        }

        public static XmlNode GetXmlNode(this XElement element)
        {

            using (XmlReader xmlReader = element.CreateReader())
            {

                XmlDocument xmlDoc = new XmlDocument();

                xmlDoc.Load(xmlReader);

                return xmlDoc;

            }

        }

        public static string ToStringAlignAttributes(this XElement element)
        {

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            settings.OmitXmlDeclaration = true;

            settings.NewLineOnAttributes = true;

            StringBuilder stringBuilder = new StringBuilder();

            using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, settings))

                element.WriteTo(xmlWriter);

            return stringBuilder.ToString();

        }

     

    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s