Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"); 
like image 775
Ishan Avatar asked Nov 22 '25 01:11

Ishan


1 Answers

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

like image 137
Habib Avatar answered Nov 23 '25 16:11

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!