2013-04-09 96 views
2

我有一個.xml文件,其結構如下。我想要獲取特定EndPointChannelID的屬性值,0.05等等。我目前能夠獲得該值,但它是針對每個EndPointChannelID而不是所需的值。另一個麻煩是讀數不總是6.我如何才能實現只存儲所需EndPointChannelID的值?任何建議將不勝感激!從c#中的.xml文件獲取多個屬性#

<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

爲什麼不使用LINQ to XML? – MarcinJuraszek 2013-04-09 17:11:29

回答

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")); 
     } 
     } 
} 
+0

完美!那正是我所需要的。感謝您的幫助! – user2262787 2013-04-09 17:25:31

0

你的代碼有點太簡單了。您需要逐行讀取並在EndPointChannelId上首先匹配。設置一個標誌以清楚地表明您具有正確的ChannelId,然後在符合條件時讀取Value屬性。你需要一個數組來保存它們。由於長度可變,所以ArrayList將是理想的。

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