“An object reference is required for the non-stati

2019-01-20 20:49发布

i am stuck with this small problem in my code.

I am trying to make small console application which will write into xml document. I have used xmldocument and xmlnode concept.

ERROR i am getting is;

*An object reference is required for the non-static field, method, or property 'Write_xml.Program.give_node(System.Xml.XmlDocument)' C:\Documents and Settings\Administrator\Desktop\Write_xml\Write_xml\Program.cs*

code is okay except 1 error. I am not able to resolve it ,i want somebody to check it and correct it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace Write_xml
{
    class Program
    {


        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            XmlDocument lets = new XmlDocument();
            string path = @"D:\XMLFile.xml";

            doc.Load(path);


            XmlNode Rootnode = doc.SelectSingleNode("Number");

            XmlNode TakenOde = give_node(doc);
            Rootnode.AppendChild(TakenOde);
            doc.Save(path);


        }


        public XmlNode give_node(XmlDocument lets)
        {
              // On this xmldoc we will perform XMLNODE operations
              // for creat new nods and append child nodes
              //XmlNode RootNode = xmldoc.CreateElement("Root");

              XmlNode PersonsNode = lets.CreateElement("Person");


              XmlNode NameNode = lets.CreateElement("Name");
              PersonsNode.AppendChild(NameNode);
              NameNode.InnerText = "1st";


              XmlNode AgeNode = lets.CreateElement("Age");
              PersonsNode.AppendChild(AgeNode);
              AgeNode.InnerText = "2nd";


              XmlNode CityNode = lets.CreateElement("City");
              PersonsNode.AppendChild(CityNode);
              CityNode.InnerText = "3rd";

              return PersonsNode;

          }

    }

}

please let me what small mistake i am doing.

1条回答
可以哭但决不认输i
2楼-- · 2019-01-20 20:59

You're trying to call an instance method, but without specifying an instance.

The simplest fix for this is to make the give_node method static.

I haven't looked at the rest of the code to see whether it's okay or not, although give_node should be called GiveNode to follow .NET naming conventions.

查看更多
登录 后发表回答