3

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"); 
Ishan
  • 4,008
  • 32
  • 90
  • 153

5 Answers5

3
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

Habib
  • 219,104
  • 29
  • 407
  • 436
2
XElement.Parse(xml).Descendants("daily")
                   .Single()
                   .Attribute("dayFrequency")
                   .Value;
cuongle
  • 74,024
  • 28
  • 151
  • 206
1
XDocument xdoc = XDocument.Parse(@"<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><daily dayFrequency=""1"" /></repeat><windowEnd>2012-10-31T10:00:00Z</windowEnd></rule></recurrence>");
        string result = xdoc
            .Descendants("recurrence")
            .Descendants("rule")
            .Descendants("repeat")
            .Descendants("daily")
            .Attributes("dayFrequency")
            .First()
            .Value;
taher chhabrawala
  • 4,110
  • 4
  • 35
  • 51
0

You should use getattribute().

For more info see : http://msdn.microsoft.com/en-us/library/acwfyhc7.aspx

0
    var nodes = xmlDoc.SelectNodes(path);

    foreach (XmlNode childrenNode in nodes)
    {
        HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//repeat").Value);
    } 
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197
Krishna Patel
  • 70
  • 1
  • 8