Recently I wanted to return a SharePoint list as an List<> of a business object.
I did some scouring on the internet, as there is no point re-inventing the wheel. But was generally disappointed with the results, as they required a lot of iterations and loops. Eric White’s blog here got me thinking, that we could do it with Linq
So here is what I did Projects my business object looks like this
| Property | Data Type |
| ProjectOwner | string |
| KPI | string |
| SKU | string |
| DateRequired | DateTime? |
| DueDate | string |
And here is the code, which expects a result set from a Sharepoint Web Service GetListItems() method.
Code Snippet
- private static List<ProjectStatus> GetProjectStatusesFromXmlNode(XmlNode resultNode)
- {
- var list = (from r in resultNode.GetXElement().Descendants()
- where r.Name.LocalName == "row"
- select new ProjectStatus
- {
- Project = (string)r.Attribute("ows_LinkTitle"),
- DateRequired = DateTime.Parse(((string)r.Attribute("ows_DateRequired"))),
- DueDate = (string)r.Attribute("ows_ECRDueDate"),
- SKU = (string)r.Attribute("ows_SKU"),
- Status = (string)r.Attribute("ows_Status"),
- ProjectOwner = (string)r.Attribute("ows_AssignedTo"),
- KPI = (string)r.Attribute("ows_tKPI")
- }
- ).ToList();
- return list;
- }
You will also need Eric White’s extension
Code Snippet
- public static class Extensions
- {
- public static XElement GetXElement(this XmlNode node)
- {
- XDocument xDoc = new XDocument();
- using (XmlWriter xmlWriter = xDoc.CreateWriter())
- node.WriteTo(xmlWriter);
- return xDoc.Root;
- }
- }
No comments:
Post a Comment