Tuesday, September 25, 2012

Query XML using LINQ

Share/Save/Bookmark


I have a scenario, to calculate the size of the documents in library.
Now after i read the library using web service in to xml (soap) i do not want to iterate or loop
all items to read the value in the column,file size. I was wondering if i can apply a aggregate function(sum)
like we have in SQL. Here is how i did with XDocument by applying LINQ on XML

XDocument xDoc = XDocument.Load("test.xml");
// Incase if source is a XmlNode
//Xdocument.Parse(XmlNode.OuterXml);
//namespace is always necesary for xdoc to identify the elements
XNamespace z = "#RowsetSchema";
var size = (from item in xDoc.Descendants(z + "row")
             select Convert.ToDouble(item.Attribute("ows_File_x0020_Size").Value.Substring(item.Attribute("ows_File_x0020_Size").Value.IndexOf('#') + 1))).Sum();

XDocument.Descendants("z:row") will always throw exception that semicolon is not allowed.
Thats one more reason why namespace should be passed.



Subscribe

No comments:

Post a Comment