簡體   English   中英

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變量中。 我在“一個”數組中僅得到一個值,所有點都寫入該數組中。 如何為每個讀取的行划分此數據?

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(),
                });

目前,您選擇的所有DayRoutinePoints的元素DayRoutine這給了你一個元素。 然后,您正在讀取其值,該值是所有嵌套點元素的值。 這就是為什么數組具有單個值。

所有您需要做的-選擇單個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
};

要解決選擇問題,您需要選擇節點<DayRoutinePoints>所有后代並獲取其值。

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

原始代碼本質上是使用DayRoutinePoints節點的內部文本,最終是該節點的內容,其中去除了所有XML。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM