Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

c# - "An object reference is required for the non-static field, method, or property"

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 SettingsAdministratorDesktopWrite_xmlWrite_xmlProgram.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...