jeudi 21 mai 2015

C# Reflection map PropertySetter to another PropertySetter

I have this simple code to read a sample .nuspec file and create a NuSpec instance of it.

static void Main(string[] args)
{

    using (var read = new System.IO.StreamReader("jsontest.nuspec", System.Text.Encoding.UTF8))
    {
        var doc = new XmlDocument();
        doc.Load(read);
        foreach (XmlElement node in doc.DocumentElement.SelectNodes("/*/metadata"))
        {
            if (node.Name == "metadata")
            {
                NuSpec n = new NuSpec();
                Fuzzy.Deserialize(node,n);
            }
        }
    }
    Console.Read();
}

This is the Fuzzy function to reflect and fill XML=>NuSpec:

public class Fuzzy
{
    public static void Deserialize(XmlElement node, object output)
    {
        foreach (XmlElement elem in node.ChildNodes)
        {
            foreach (var info in output.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                if (info.Name.ToLower().Equals(elem.Name.ToLower()))  //variable name matches node name
                {
                    info.SetValue(output, elem.InnerText,null);
                }
            }
        }
    }
}

What I want is in Fuzzy function after info.SetValue() to create a mapping from info.GetSetMethod() => elem.InnerText.GetSetMethod(). If I now change my NuSpec n.Id = "Hello" it would call elem.Innertext = "Hello";

This is the .nuspec file:

<?xml version="1.0"?>
<package >
  <metadata>
    <id>ETASSharedLib_src</id>
    <version>1.2.0.0</version>
    <title>ETAS Shared Library</title>
    <authors>ETAS Group</authors>
    <owners>ETAS Group</owners>
    <licenseUrl>http://LICENSE_URL_HERE_OR_DELETE_THIS_LINE</licenseUrl>
    <projectUrl>http://PROJECT_URL_HERE_OR_DELETE_THIS_LINE</projectUrl>
    <iconUrl>http://ICON_URL_HERE_OR_DELETE_THIS_LINE</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>ETAS common library</description>
    <releaseNotes>Latest version contains support for INCA NextGen features</releaseNotes>
    <copyright>Copyright 2015</copyright>
    <tags>ETASSharedLib Source INCA</tags>
  </metadata>
</package>




Aucun commentaire:

Enregistrer un commentaire