获取xml节点值

时间:2013-03-28 14:30:40

标签: c# xpath xml-parsing xml-serialization linq-to-xml

下面的xml有一个属性Itemcount(<rs:data ItemCount="4">)。我如何通过代码获得价值。 xmldocument.childnodes.count没有给我正确的计数

我需要得到子节点的计数,即Itemcount

    <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="4">

   <z:row ows_Attachments="0" ows_UniqueId="1;#{DF5B35E4-D3EB-4E16-9D6F-23F368CDE05C}"/>


 <z:row ows_Attachments="0" ows_UniqueId="2;#{83803774-A2F6-4265-AD73-E8600ECFCE04}"/>


<z:row ows_Attachments="0"  ows_UniqueId="3;#{8B1C0737-EAA2-4313-BEC3-A5A907341856}"/>

 <z:row ows_Attachments="0"  ows_UniqueId="5;#{65CA20E9-E427-412C-A98B-367DDEBE8911}"/>

</rs:data>
</listitems>

1 个答案:

答案 0 :(得分:1)

//xmlStr contains your xml as a string
var xml = XDocument.Parse(xmlStr);

XNamespace rs = "urn:schemas-microsoft-com:rowset";

string[] result = xml.Descendants(rs + "data")
                     .Select(node => node.Attribute("ItemCount").Value)
                     .ToArray();

Console.WriteLine(string.Join(Environment.NewLine, result));

打印:

4