我有一个带有以下结构的.xml文件。我想获取特定EndPointChannelID的属性值,0.05等等。我目前能够获得值,但它适用于每个EndPointChannelID而不是所需的值。另一个转折是读数并不总是为6.我如何只实现存储所需EndPointChannelID的值?任何建议将不胜感激!
<Channel ReadingsInPulse="false">
<ChannelID EndPointChannelID="5154131" />
<ContiguousIntervalSets>
<ContiguousIntervalSet NumberOfReadings="6">
<TimePeriod EndRead="11386.22" EndTime="2013-01-15T02:00:00Z"/>
<Readings>
<Reading Value="0.05" />
<Reading Value="0.04" />
<Reading Value="0.05" />
<Reading Value="0.06" />
<Reading Value="0.03" />
<Reading Value="0.53" />
</Readings>
</ContiguousIntervalSet>
</ContiguousIntervalSets>
</Channel>
以下是我必须找到的值的当前代码。
XmlReader reader = XmlReader.Create(FileLocation);
while (reader.Read())
{
if((reader.NodeType == XmlNodeType.Element) && (reader.Name == "Reading"))
{
if (reader.HasAttributes)
{
MessageBox.Show(reader.GetAttribute("Value"));
}
}
}
答案 0 :(得分:1)
继续XMLReader
路径,您可以通过设置结果列表,等待所需的通道ID,开始收集值,然后在所需的通道ID标记结束时结束收集它们来实现:
var values = new List<string>();
var collectValues = false;
var desiredChannelId = "5154131";
while (reader.Read())
{
if((reader.NodeType == XmlNodeType.Element))
{
if (reader.Name == "ChannelID" && reader.HasAttributes) {
collectValues = reader.GetAttribute("EndPointChannelID") == desiredChannelId;
}
else if (collectValues && reader.Name == "Reading" && reader.HasAttributes)
{
values.Add(reader.GetAttribute("Value"));
}
}
}
答案 1 :(得分:0)
您的代码太简单了。您需要逐行读取并在EndPointChannelId上首先匹配。设置一个标志以清楚地表明您拥有正确的ChannelId,然后,当满足该条件时,请阅读Value
属性。你需要一个数组来保存它们。 ArrayList
是理想的,因为它的长度可变。
答案 2 :(得分:0)
可以使用LINQ to XML轻松完成:
// load document into memory
var xDoc = XDocument.Load("Input.txt");
// query the document and get List<decimal> as result
List<decimal> values = (from ch in xDoc.Root.Elements("Channel")
where (int)ch.Element("ChannelID").Attribute("EndPointChannelID") == 5154131
from r in ch.Descendants("Reading")
select (decimal)r.Attribute("Value")).ToList();