Kerberos
Kerberos

Reputation: 1256

Invoke Method from xml file

I have a xml file which is name Methods.xml as below

....
<Method>
        <MethodName>foo</MethodName>
        <MethodParams>fooString1, fooString2</MethodParams>
</Method>
<Method>
        <MethodName>foo</MethodName>
        <MethodParams>fooString5, fooString6</MethodParams>
</Method>
    ....

and i have method as below

 void foo(string param1, string param2)
 {
    MessageBox.Show(param1 +" : " + param2);
 }

I can get node values as below and i would like to invoke method dynamically according to xml file node's value

XDocument _XDocument = XDocument.Load(@"Methods.xml");

var _XmlQuery = from _Element in _XDocument.Descendants("Method")
                select
                    new
                    {
                        _MethodName = _Element.XPathEvaluate("string(./MethodName)") as string,
                        _MethodParams = _Element.XPathEvaluate("string(./MethodParams)") as string,

                    };


foreach (var _Node in _XmlQuery)
{

    string _MethodName = _Node._Method.Trim();
    MethodInfo _Method = this.GetType().GetMethod(_MethodName);

    List<object> _Params = new List<object>();
    object[] _XmlParams = _Nodes.MethodParams.Split(',');
    foreach (object arg in XmlParams)
    {
        _Params.Add(arg);
    }
    _Method.Invoke(this, _Params.ToArray());

}

but when i debug, i get error in this _Method.Invoke(this, _Params.ToArray()); line.

Thanks in advance.

EDITED

Error Message is: Object reference not set to an instance of an object.

Upvotes: 2

Views: 2140

Answers (2)

Tomtom
Tomtom

Reputation: 9394

I tried it with a simple winforms-application with just one button on it. In the click-event the method foo is called. Here's the code:

 private void button1_Click(object sender, EventArgs e)
    {
        MethodInfo val = this.GetType().GetMethod("Foo");
        val.Invoke(this, new object[] {"1", "2"});
    }

    public void Foo(string p1, string p2)
    {
        MessageBox.Show("");
    }

And it works perfectly. If I make Foo private than i get the same execption as you. So you can either make Foo public or you have to set the BindingFlags.Public, BindingFlags.NonPublic and BindingFlags.Instance at the GetMethod-Method

Upvotes: 2

Nick Butler
Nick Butler

Reputation: 24403

By default, Type.GetMethod( string ) only return methods marked as public.

You need to pass some BindingFlags options:

...GetMethod( _MethodName,
  BindingFlags.Public |
  BindingFlags.NonPublic |
  BindingFlags.Instance
);

Upvotes: 3

Related Questions