78 lines
2.7 KiB
C#
78 lines
2.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Xml.Linq;
|
|
|
|
namespace WindowsService1
|
|
{
|
|
public class XmlConfigReader
|
|
{
|
|
private Dictionary<string, Dictionary<string, Dictionary<string, string>>> deviceData;
|
|
|
|
public XmlConfigReader(string xmlContent)
|
|
{
|
|
XDocument doc = XDocument.Parse(xmlContent);
|
|
deviceData = ReadXmlToNestedDictionary(doc);
|
|
}
|
|
|
|
public XmlConfigReader(XDocument doc)
|
|
{
|
|
deviceData = ReadXmlToNestedDictionary(doc);
|
|
}
|
|
|
|
private Dictionary<string, Dictionary<string, Dictionary<string, string>>> ReadXmlToNestedDictionary(XDocument doc)
|
|
{
|
|
var result = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
|
|
var mainDevice = doc.Root.Element("Device");
|
|
string mainDeviceName = mainDevice.Attribute("name").Value;
|
|
result[mainDeviceName] = new Dictionary<string, Dictionary<string, string>>();
|
|
|
|
foreach (var subDevice in mainDevice.Elements("Device"))
|
|
{
|
|
string subDeviceName = subDevice.Attribute("name").Value;
|
|
result[mainDeviceName][subDeviceName] = new Dictionary<string, string>();
|
|
|
|
foreach (var type in subDevice.Elements("Type"))
|
|
{
|
|
string typeName = type.Attribute("name").Value;
|
|
string typeValue = type.Value;
|
|
result[mainDeviceName][subDeviceName][typeName] = typeValue;
|
|
}
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
public void PrintStructure()
|
|
{
|
|
foreach (var mainDevice in deviceData)
|
|
{
|
|
Console.WriteLine($"Main Device: {mainDevice.Key}");
|
|
foreach (var subDevice in mainDevice.Value)
|
|
{
|
|
Console.WriteLine($" Sub Device: {subDevice.Key}");
|
|
foreach (var type in subDevice.Value)
|
|
{
|
|
Console.WriteLine($" Type: {type.Key}, Value: {type.Value}");
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public bool TryGetValue(string mainDeviceName, string subDeviceName, string typeName, out string value)
|
|
{
|
|
value = null;
|
|
return deviceData.TryGetValue(mainDeviceName, out var mainDevice) &&
|
|
mainDevice.TryGetValue(subDeviceName, out var subDevice) &&
|
|
subDevice.TryGetValue(typeName, out value);
|
|
}
|
|
|
|
public Dictionary<string, Dictionary<string, Dictionary<string, string>>> GetAllData()
|
|
{
|
|
return deviceData;
|
|
}
|
|
}
|
|
}
|