且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过linq读取XML属性

更新时间:2022-11-27 09:24:22

您可以使用 
XDocument
使用LINQ迭代每一行,并找到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(x zocument.Element中的var zRow(" {http://schemas.microsoft.com/sharepoint/soap/} listitems").Element(" {urn:schemas-microsoft- com:rowset} data")。Elements())
{
// TODO:XML中每条记录的流程标题。
string title = zRow.Attribute(" ows_Title")。Value;
}


修改:我编写了foreach循环来阐明XML模式允许多行;如果确定只有一行,您可以使用以下代码来获取标题:

 string title = xDocument 
.Element(" { http://schemas.microsoft.com/sharepoint/soap/}listitems")
.Element(" {urn:schemas-microsoft-com:rowset} data")
.Elements()。 。单()属性(" ows_Title&QUOT)值;


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


Er.vinay

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;