Read an XML string in C#

Ishan picture Ishan · Oct 30, 2012 · Viewed 35k times · Source

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"); 

Answer

Habib picture Habib · Oct 30, 2012
XDocument xmlDoc = XDocument.Parse(xml);
var val = xmlDoc.Descendants("daily")
                .Attributes("dayFrequency")
                .FirstOrDefault();

Here val will be:

val = {dayFrequency="1"}

val.Value will give you 1