在c#中从.xml文件中获取多个属性

本文关键字:获取 属性 文件 中从 xml | 更新日期: 2023-09-27 18:08:11

我有一个结构如下的.xml文件。我想获得属性值,0.05等,为特定的EndPointChannelID的。我目前能够得到的值,但它是为每一个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"));
                 }
              }
        }

在c#中从.xml文件中获取多个属性

继续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"));
         }
      }
}

你的代码有点太简单了。您需要逐行读取并首先匹配EndPointChannelId。设置一个标志以明确您拥有正确的ChannelId,然后,当满足该条件时,读取Value属性。您需要一个数组来保存它们。ArrayList是理想的,因为它是可变长度的。

使用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();