Home > Software engineering >  Get Hierarchy from XML file C#
Get Hierarchy from XML file C#

Time:06-22

I have an xml structure like this:

<Plugin Name="Test">
        <Configuration>
            <Parameter Name="Dummy" Value="1">
                <Parameter Name="Test11" Value="2"/>
                <Parameter Name="Test12" Value="4"/>
                <Parameter Name="Test12" Value="6"/>
            </Parameter>
        </Configuration>
</Plugin>

and I have a configuration class like this:

[Serializable]
public class PluginConfiguration
{
    [XmlElement("Parameter")]
    public virtual List<Parameter> Parameters { get; set; }
}

now I want to write extension methods for my PluginConfiguration class like this:

con.GetValue("Dummy");

this should return 1 and

con.GetValue("Dummy/Test11");

this should return 2 and

con.GetValues("Dummy/Test12");

should return collection of [4,6]

here is my code:

public object GetValue(string arg1)
    {
        arg1 = "Dummy/Test11";           
        string[] splittedArg = arg1.Split('/');

        if (splittedArg.Length == 0) return "";

        string firstParamName = splittedArg[0];
        string lastParamName = splittedArg[splittedArg.Length - 1];
        
        foreach (Parameter param in pluginConfiguration.Parameters)
        {
            if (param.Name == firstParamName)
            {
                if (splittedArg.Length == 1)
                {
                    return param.Value;
                }
                foreach (Parameter param1 in param.Parameters)
                {
                    if (param1.Name == lastParamName)
                    {
                        return param1.Value;
                    }
                }
            }
        }
        return "";
    }

CodePudding user response:

public List<string> GetValue(string arg1)
{
    if(string.IsNullOrEmpty(arg1))
        return null;

    arg1 = "Dummy/Test11";           
    var splittedArg = arg1.Split('/');

    var firstParamName = splittedArg.FirstOrDefault();
    var lastParamName = splittedArg.Count() > 1 ? splittedArg.LastOrDefault() : null;

    var firstLevelParameters = pluginConfiguration.Parameters.Where(p=>p.Name == firstParamName);

    var returnList = new List<string>();
    
    foreach (Parameter param in firstLevelParameters)
    {
         if (lastParamName == null)
         {
              returnList.Add(param.Value);
         }
         else
         {
              foreach (var subParam in param.Parameters.Where(x=>x.Name == lastParamName))
              {
                   returnList.Add(subParam.Value);
                   //probably would make more sense to add the first level value as well 
                   //returnList.Add($"{param.Value}/{subParam.Value}");
                   //
                   //in your case this would be "1/2"
              }
         }
    
    }
    return returnList;
}
  • Related