Search code examples
c#asp.netxmlreadxml

Read an XML string in C#


I have a string of type string xml = @"<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><daily dayFrequency=""1"" /></repeat><windowEnd>2012-10-31T10:00:00Z</windowEnd></rule></recurrence>";

I want to read dayFrequency value which is 1 here, is there a way i can directly read dayFrequency under the tag daily and likewise there are many such tags such as a="1", b="King" etc. so i want to read directly the value assigned to a variable.

Kindly help.

The below code i used which reads the repeat tag

string xml = @"<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><daily dayFrequency=""1"" /></repeat><windowEnd>2012-10-31T10:00:00Z</windowEnd></rule></recurrence>";

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);

// this would select all title elements
XmlNodeList titles = xmlDoc.GetElementsByTagName("repeat"); 

Solution

  • XElement.Parse(xml).Descendants("daily")
                       .Single()
                       .Attribute("dayFrequency")
                       .Value;