2017-10-15 86 views
-1

我試圖獲取項目「終端ID」和「當前配置」的值,並將它們分配給一個變量。C#讀取xml文件並將值分配給變量

我在互聯網上發現了不同的例子,但沒有人得到我想要的結果。

XML文件:

<TerminalOverview xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.App.Home.Model"> 
    <InfoItems> 
    <InfoItem> 
     <Name>Device name</Name> 
     <Value/> 
    </InfoItem> 
    <InfoItem> 
     <Name>Terminal ID</Name> 
     <Value>253896528</Value> 
    </InfoItem> 
    <InfoItem> 
     <Name>Current Configuration</Name> 
     <Value>BmtVersion - 1.1.32</Value> 
    </InfoItem> 
    <InfoItem> 
     <Name>Local Time</Name> 
     <Value>15/10/2017 13:58:14</Value> 
    </InfoItem> 
    <InfoItem> 
     <Name>Time zone</Name> 
     <Value>Amsterdam</Value> 
    </InfoItem> 
    </InfoItems> 
    <Message xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.Common.Models" i:nil="true"/> 
    <Success xmlns="http://schemas.datacontract.org/2004/07/Bmt.BmtSharp.WebInterface.Backend.API.Common.Models">true</Success> 
</TerminalOverview> 

我想「終端ID」的值賦給變量terminalID和「當前配置」的值賦給變量softwareVersion。

我該如何做到這一點?

+0

的可能的複製[如何獲得在字符串中的XML節點的值(https://stackoverflow.com/questions/17590182/how-to-get-the-xml-node-value-in-string ) – Alexander

+0

你是什麼意思,你發現很多例子,但沒有你想要的?你可以在你讀取xml節點的地方顯示代碼嗎? –

回答

0

下面的代碼將把所有的項目放到一個字典中。然後你可以從字典中獲得id和配置。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Xml; 
using System.Xml.Linq; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     const string FILEMNAME = @"c:\temp\test.xml"; 
     static void Main(string[] args) 
     { 
      XDocument doc = XDocument.Load(FILEMNAME); 

      XElement root = doc.Root; 
      XNamespace ns = root.GetDefaultNamespace(); 

      Dictionary<string, string> dict = root.Descendants(ns + "InfoItem") 
       .GroupBy(x => (string)x.Element(ns + "Name"), y => (string)y.Element(ns + "Value")) 
       .ToDictionary(x => x.Key, y => y.FirstOrDefault()); 
     } 
    } 
} 
相關問題