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");
解決
XElement.Parse(xml).Descendants("daily")
.Single()
.Attribute("dayFrequency")
.Value;
他のヒント
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
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;
You should use getattribute().
For more info see : http://msdn.microsoft.com/en-us/library/acwfyhc7.aspx
var nodes = xmlDoc.SelectNodes(path);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//repeat").Value);
}
所属していません StackOverflow