This is my requirement: Write a program that accepts an XML input string and get all node values by name from it. Use the namespace System.XML ( Do not use System.XML.Linq).
Display & node values separated by space.
Example: If input string contains following string:
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName</Name>
<Name><FirstName>James</FirstName> <LastName>White</LastName></Name></Names>
Display output as : John Smith James White
Create a class named UserProgramCode that has the following static method public static string getnodeByName(string input1) Create a class named Program that accepts the inputs and calls the static method present in the UserProgramCode.
And My code is
using System; using System.Xml;
public class Program{
public static void Main(){
string xmlinput=Console.ReadLine();
UserProgramCode.getnodeByName(xmlinput);
}
}
public class UserProgramCode{
static string ResultName;
public static string getnodeByName(string input1)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(input1);
string xpath ="Names/Name";
var nodes = xmlDoc.SelectNodes(xpath);
foreach (XmlNode childrenNode in nodes)
{
UserProgramCode.ResultName=childrenNode.SelectSingleNode("/FirstName").InnerText +" "+ childrenNode.SelectSingleNode("/LastName").InnerText;
}
return UserProgramCode.ResultName;
}
}
But I am getting Null reference Exception.I have no idea how to resolve this. Please help . I am new to C#.net.
John Smith James White Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object at UserProgramCode.getnodeByName (System.String input1) [0x00000] in :0 at Program.Main () [0x00000] in :0 [ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object at UserProgramCode.getnodeByName (System.String input1) [0x00000] in :0 at Program.Main () [0x00000] in :0