在C#中读取XML字符串

3

我有一个字符串,类型为string xml = @"<recurrence><rule><firstDayOfWeek>mo</firstDayOfWeek><repeat><daily dayFrequency=""1"" /></repeat><windowEnd>2012-10-31T10:00:00Z</windowEnd></rule></recurrence>"

我想要读取dayFrequency的值,在这里是1。是否有一种方式可以直接读取标签daily下的dayFrequency值,而且还有许多类似的标签,如a="1",b="King"等等。因此,我希望能直接读取分配给变量的值。

请帮忙。

我使用了下面的代码来读取重复标签:

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

你的代码出了什么问题? - L.B
dayFrequency=""1"" 是错误的。如果我没记错," 需要编码为 "。 - Lloyd
为什么不使用XLinq呢? - manman
5个回答

3
XDocument xmlDoc = XDocument.Parse(xml);
var val = xmlDoc.Descendants("daily")
                .Attributes("dayFrequency")
                .FirstOrDefault();

在这里,“val”将是:
val = {dayFrequency="1"}

val.Value将会给你返回1


2
XElement.Parse(xml).Descendants("daily")
                   .Single()
                   .Attribute("dayFrequency")
                   .Value;

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;

0
    var nodes = xmlDoc.SelectNodes(path);

    foreach (XmlNode childrenNode in nodes)
    {
        HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("//repeat").Value);
    } 

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接