简体   繁体   中英

C# Read xml file and assign values to variables

I am trying to get the value of the item "Terminal ID" and "Current Configuration" and assign them to a variable.

I have found different examples on the internet but no one have the result what i want.

XML File:

<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>

I want the Value of "Terminal ID" to be assigned to variable terminalID and the value of "Current Configuration" to be assigned to variable softwareVersion.

How can I achieve this?

The code below will put all the items int a dictionary. Then you can get the id and configuration from the dictionary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM