-1

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?

  • Possible duplicate of [How to get the xml node value in string](https://stackoverflow.com/questions/17590182/how-to-get-the-xml-node-value-in-string) – Alexander Oct 15 '17 at 13:56
  • What do you mean you found many examples but none are what you want? Can you show the code where you read the xml nodes? – display name Oct 15 '17 at 14:02

1 Answers1

0

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());
        }
    }
}
jdweng
  • 33,250
  • 2
  • 15
  • 20