How can i read the XML attribute through linq

Category: c# language

Question

Er. Vinay Kumar on Thu, 18 Oct 2012 07:27:28


Hi Expert,

How can i read the xml using linq.

The xml is :-

<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="1">
   <z:row ows_Title="Test2" ows_MetaInfo="3;#" ows__ModerationStatus="0" ows__Level="1" ows_ID="3" ows_UniqueId="3;#{98C4E256-5AF7-4415-B760-F533A50C28A1}" ows_owshiddenversion="1" ows_FSObjType="3;#0" ows_Created="2012-10-17T10:18:13Z" ows_PermMask="0x7fffffffffffffff" ows_Modified="2012-10-17T10:18:13Z" ows_FileRef="3;#Lists/Vinay kumar/3_.000" />
</rs:data>
</listitems>

I would like to find out ows_Title="Test2" through LINQ.

Thanks

Replies

John Michael Bird on Thu, 18 Oct 2012 08:45:21


You can use an XDocument to iterate through each row with LINQ, and find the values of ows_Title:

System.Xml.Linq.XDocument xDocument; using (System.IO.StringReader reader = new System.IO.StringReader(xmlString)) xDocument = System.Xml.Linq.XDocument.Load(reader); foreach (var zRow in xDocument.Element("{http://schemas.microsoft.com/sharepoint/soap/}listitems").Element("{urn:schemas-microsoft-com:rowset}data").Elements()) { //TODO: Process title for each record in XML. string title = zRow.Attribute("ows_Title").Value; }

Edit: I wrote the foreach loop to clarify that the XML schema allowed multiple rows; if it's certain there is only one row, you could use the following code to get the title:

string title = xDocument
    .Element("{http://schemas.microsoft.com/sharepoint/soap/}listitems")
    .Element("{urn:schemas-microsoft-com:rowset}data")
    .Elements().Single().Attribute("ows_Title").Value;

MasaSam on Fri, 19 Oct 2012 16:43:26


You don't even need to use foreach loop. You can directly query the attribute by name and value.

For example

            var row = document.Element("{http://schemas.microsoft.com/sharepoint/soap/}listitems")
                              .Element("{urn:schemas-microsoft-com:rowset}data")
                              .Elements()
                              .Attributes()
                              .Where(x => x.Name == "ows_Title")
                              .Where(x => x.Value == "Test2")
                              .FirstOrDefault();

Lisa Zhu on Wed, 24 Oct 2012 08:59:08


Hi Er.vinay,

From your description , I ‘d like to move this post to  the most related forum for better support .

Thanks for your understanding .

Regards ,