XDocument 加载到 ToList

XDocument Load to ToList

我正在借助 XDocument 加载 .xml 文件。我成功读取了 .xml 文件。

C#代码:

XDocument doci = XDocument.Load(path);
var mijav = from r in doci.Descendants("Configuration").Descendants("DayRoutine").Descendants("DayRoutine").Where(r => (int)r.Attribute("ID") == 4)
            select new
            {
                Button = r.Element("Button").Value,
                DataPoints = r.Elements("DayRoutinePoints").Select(c => (string)c.Value).ToList(),
            };

我遇到的问题是 DataPoint 变量。我在 "one" 数组中只得到一个值,所有的点都写在这个数组中。如何为每个读取的行划分此数据?

DataPoint 变量现在:

"00:00:00, 44004:45:00, 48013:35:00, 60015:00:00, 41519:55:00, 600"

XML 中的积分数据以及我喜欢的方式:

"00:00:00, 440
 04:45:00, 480
 13:35:00, 600
 15:00:00, 415
 19:55:00, 600"

我的 XML 文件:

<blabla>
   <Infos>
      <ConfigurationName>XXConfigurationName</ConfigurationName>
     <DateSaved>14.10.2015 13:14:01</DateSaved>
   </Infos>
 <Configuration>
    <DayRoutine>
       <DayRoutine ID="4">
          <Button>1</Button>
          <SetupOption>StaticBasic_DoffEoff</SetupOption>
          <DayRoutinePoints>
             <Point0>00:00:00, 440</Point0>
             <Point1>04:45:00, 480</Point1>
             <Point2>13:35:00, 600</Point2>
             <Point3>15:00:00, 415</Point3>
             <Point4>19:55:00, 600</Point4>
          </DayRoutinePoints>
       </DayRoutine>
   </DayRoutine>
  </Configuration>
</blabla>

使用这个:

DataPoints = String.Join(" ", r.Elements("DayRoutinePoints")
.Elements()
.Select(x=>x.Value.ToString()+Environment.NewLine))

试试这个:

XDocument doci = XDocument.Load(path);
        var mijav =
            doci.Descendants("Configuration")
                .Descendants("DayRoutine")
                .Descendants("DayRoutine")
                .Where(r => (int) r.Attribute("ID") == 4)
                .Select(r => new
                {
                    Button = r.Element("Button").Value,
                    DataPoints =
                        r.Elements("DayRoutinePoints").Elements()
                            .Select(c => (string) c.Value)
                            .ToList(),
                });

目前您正在 selecting DayRoutine 的所有 DayRoutinePoints 个元素,这给您一个元素。然后您正在读取它的值,即所有嵌套点元素的值。这就是为什么你有单值数组。

您需要做的就是 - select 单个 DayRoutinePoints 元素并获取它的子元素:

DataPoints = r.Element("DayRoutinePoints").Elements().Select(c => (string)c).ToList(),

注意:使用 XPath,您的解析看起来会更简单(我也省略了将点转换为列表)

from r in doci.XPathSelectElements("//Configuration/DayRoutine/DayRoutine[@ID=4]")    
select new
{
    Button = (string)r.Element("Button"),
    DataPoints = from p in r.Element("DayRoutinePoints").Elements()
                 select (string)p
};

要解决 selection 问题,您需要 select 节点 <DayRoutinePoints> 的所有后代并获取它们的值。

DataPoints = r.Descendants("DayRoutinePoints")
              .Descendants().Select(c => (string)c.Value).ToList(),

原始代码本质上是获取 DayRoutinePoints 节点的内部文本,最终成为删除所有 XML 的节点内容。