在 C# 中读取 XML 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13136920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read an XML string in C#
提问by Ishan
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>";
我有一个类型的字符串 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 dayFrequencyvalue which is 1here, is there a way i can directly read dayFrequencyunder the tag dailyand 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.
我想读取这里的dayFrequency值1,有没有办法可以直接dayFrequency在标签下读取daily,同样有很多这样的标签,例如a="1"、b="King"等,所以我想直接读取值赋值给一个变量。
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");
采纳答案by cuongle
XElement.Parse(xml).Descendants("daily")
.Single()
.Attribute("dayFrequency")
.Value;
回答by Wilko de Zeeuw
You should use getattribute().
您应该使用 getattribute()。
For more info see : http://msdn.microsoft.com/en-us/library/acwfyhc7.aspx
有关更多信息,请参阅:http: //msdn.microsoft.com/en-us/library/acwfyhc7.aspx
回答by Krishna Patel
var nodes = xmlDoc.SelectNodes(path);
foreach (XmlNode childrenNode in nodes)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//repeat").Value);
}
回答by Habib
XDocument xmlDoc = XDocument.Parse(xml);
var val = xmlDoc.Descendants("daily")
.Attributes("dayFrequency")
.FirstOrDefault();
Here val will be:
这里 val 将是:
val = {dayFrequency="1"}
val.Valuewill give you 1
val.Value会给你 1
回答by taher chhabrawala
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;

