XDocument加载到列表
本文关键字:列表 加载 XDocument | 更新日期: 2023-09-27 18:17:35
我在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(),
};
我的问题是在数据点变量。我在"one"数组中只得到一个值,所有的点都写在这个数组中。如何为每个已读行划分此数据?
数据点变量现在:
"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"
My XML file:
<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>
试试这个:
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>
的所有后代并获取它们的值。
DataPoints = r.Descendants("DayRoutinePoints")
.Descendants().Select(c => (string)c.Value).ToList(),
原始代码本质上是采用DayRoutinePoints
节点的内部文本,它最终是去掉所有XML的节点内容。
使用
DataPoints = String.Join(" ", r.Elements("DayRoutinePoints")
.Elements()
.Select(x=>x.Value.ToString()+Environment.NewLine))
目前您正在选择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
};