2015-10-14 72 views
1

我正在使用XDocument加載.xml文件。我成功讀取了.xml文件。將XDocument加載到ToList

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

問題我是在數據點變量。我在「一個」數組中只有一個值,並且所有的點都寫在這個數組中。如何爲每條聯合生產線劃分這些數據?

數據點現在變量:

"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> 
+0

是否總有5個編號爲0-4的點? – theB

+0

在這種情況下,它始終是5分 – esispaned

+0

您需要選擇DayRoutinePoints的元素並將它們全部放在1個字符串中,可以使用'Environment.NewLine' – singsuyash

回答

1

試試這個:

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

使用此:

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

目前您選擇的DayRoutine所有DayRoutinePoints元素,讓你單元素。然後你正在讀取它的值,它是所有嵌套點元素的值。這就是爲什麼你有單個值的數組。

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

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

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

原始代碼基本上取DayRoutinePoints節點,其最終被所述節點的與剝離出來的所有XML內容的內部文本。