I am trying to return the the attribute values from this XML, which is a collection of XmlNodes called from a Sharepoint Webmethod.
XML Data
<Lists xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<List DocTemplateUrl="" DefaultViewUrl="/Lists/Announcements/AllItems.aspx" MobileDefaultViewUrl="" ID="{E6172717-EB95-4845-B8CB-8161832565C6}" Title="Announcements" Description="Use the Announcements list to post messages on the home page of your site." ImageUrl="/_layouts/images/itann.gif" Name="{E6172717-EB95-4845-B8CB-8161832565C6}" BaseType="0" FeatureId="00bfea71-d1ce-42de-9c63-a44004ce0104" />
<List DocTemplateUrl="" DefaultViewUrl="/Lists/Calendar/calendar.aspx" MobileDefaultViewUrl="" ID="{C0735477-BE48-4DDF-9D93-3E1F8E993CEC}" Title="Calendar" Description="Use the Calendar list to keep informed of upcoming meetings, deadlines, and other important events." ImageUrl="/_layouts/images/itevent.gif" Name="{C0735477-BE48-4DDF-9D93-3E1F8E993CEC}" BaseType="0" FeatureId="00bfea71-ec85-4903-972d-ebe475780106" />
///... Several more like this
</Lists>
I have been following a few different guides, just been going through like this one on DiC, and I've managed to get the examples to work.
public List<Dictionary<string, XmlAttribute>> GetListData(XmlNode collection)
{
#region Test
string nodeInput = Convert.ToString(collection.OuterXml);
TextReader sr = new StringReader(nodeInput);
//from <List> node, decendant of <Lists>
var lists = (from list in XElement.Load(sr).Descendants("List")
//where the baseType element value equals 0
where int.Parse(list.Element("BaseType").Value) == 0
//Output the titles values to a list
select list.Element("Title").Value).ToList();
}
#endregion
I've been trying to adapt a few of the examples to my data to get more of an idea how it works, but this query has not returned any results unlike I expected. I've written besides each line in a comment what I thought the command was doing, could someone illuminate my mistake?
Solution
Very easy to find once I knew namespace was the issue.
http://msdn.microsoft.com/en-us/library/bb669152.aspx C# unlike VB requires the namespace even when the nodes aren't prefixed by it.
So I needed an XNamespace
XNamespace nameSpace = "http://schemas.microsoft.com/sharepoint/soap/";
XElement node = XElement.Parse(nodeInput);
var lists = from list in node.Descendants(nameSpace + "List")
select list;
foreach (var list in lists)
{
var doc = list.Document;
}
Your code should be
XNamespace ns = "http://schemas.microsoft.com/sharepoint/soap/";
var lists = (from list in XElement.Parse(nodeInput).Descendants(ns + "List")
where (int)list.Attribute(ns + "BaseType") == 0
select (string)list.Attribute(ns + "Title")).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With