【问题标题】:C# - Cycle through and get values of XML values with same nameC# - 循环并获取具有相同名称的 XML 值的值
【发布时间】:2018-09-10 20:30:40
【问题描述】:

我正在尝试从这样布局的 XML 文档中获取一些值

<Work>
    <Name>Group Work</Name>
    <Data>
        <Day>
            <Attended>7</Attended>
            <StartTime>12:00</StartTime>
            <Date>01-01-2018</Date>
        </Day>
        <Day>
            <Attended>4</Attended>
            <StartTime>11:00</StartTime>
            <Date>02-01-2018</Date>
        </Day>
        <Day>
            <Attended>11</Attended>
            <StartTime>13:00</StartTime>
            <Date>03-01-2018</Date>
        </Day>
    </Data>
</Work>

我想单独取出每一天的数据。

即取出每个会话的参加者人数并计算平均值,同时仍显示相应日期的参加人数。

到目前为止,我已经设法使用以下代码取出第一个 &lt;Attended&gt; 值:

XmlNode attendedValue = xml.SelectSingleNode("/Work/Data/Day/Attended");

但我不确定如何在每个&lt;Day&gt; 中循环并获取其独特价值。是否可以按日期过滤这些?

【问题讨论】:

标签: c# xml xpath


【解决方案1】:

试试 xml linq:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);

            Dictionary<string, Dictionary<DateTime, int>> dict = doc.Descendants("Work")
                .GroupBy(x => (string)x.Element("Name"), y => y.Descendants("Day")
                    .GroupBy(a => ((DateTime)a.Element("Date")).Add((new TimeSpan(((DateTime)a.Element("StartTime")).Hour,((DateTime)a.Element("StartTime")).Minute,0))), b => (int)b.Element("Attended"))
                    .ToDictionary(a => a.Key, b => b.FirstOrDefault()))
                    .ToDictionary(x => x.Key, y => y.FirstOrDefault());

         }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    • 2022-01-08
    • 2012-12-30
    • 1970-01-01
    相关资源
    最近更新 更多