2017-10-15 91 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()); 
     } 
    } 
} 
相关问题