我在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>
答案 0 :(得分:1)
使用此:
DataPoints = String.Join(" ", r.Elements("DayRoutinePoints")
.Elements()
.Select(x=>x.Value.ToString()+Environment.NewLine))
答案 1 :(得分: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(),
});
答案 2 :(得分:1)
目前,您正在选择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
};
答案 3 :(得分:1)
要解决选择问题,您需要选择节点<DayRoutinePoints>
的所有后代并获取它们的值。
DataPoints = r.Descendants("DayRoutinePoints")
.Descendants().Select(c => (string)c.Value).ToList(),
原始代码基本上采用了DayRoutinePoints
节点的内部文本,最终成为节点的内容,并删除了所有XML。