Andromelus Andromelus - 1 year ago 102
C# Question

Xml and C#, extracting a value

I have a very simple XML document:


I'm trying to extract one value from the document, but what ever the method I use, the return is N
ullReferenceException: Object reference not set to an instance of an object

I tried using this method:
Or this methods:

There is the code I have now:

public string Get_Xml_Value(string Value_To_Get)
string Xml_File = File.ReadAllText(GMS_Script.Player_Name + ".xml");
XmlDocument Xml_Doc = new XmlDocument();
XmlNodeList Xml_Node_List = Xml_Doc.SelectNodes("Player_Stats");
return Xml_Node_List[3].InnerText;


Could someone tell me what I am doing wrong? Thanks.

NB: The firt site I used uses strings and Xml_Node_List["Something"], but Visual studio tells me it should be an index...

Answer Source

Your XPath returns the root node, but you want the children of it. So it should be something like this

XmlNodeList Xml_Node_List = Xml_Doc.SelectNodes("Player_Stats/*");

Said that, I find Linq2Xml easier to use...

var xDoc = XDocument.Load(filename);
var val1 = (int)xDoc.XPathSelectElement("/Player_Stats/Ship_Resistance");
var val2 = (string)xDoc.XPathSelectElement("/Player_Stats/Player_Faction");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download