Andromelus Andromelus - 1 month ago 7
C# Question

Xml and C#, extracting a value

I have a very simple XML document:

<Player_Stats>
<Player_Name>test</Player_Name>
<Player_Faction>Melrehn</Player_Faction>
<Ship_Damages>10</Ship_Damages>
<Ship_Resistance>10</Ship_Resistance>
</Player_Stats>


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: http://www.csharp-examples.net/xml-nodes-by-name/
Or this methods: http://csharp.net-tutorials.com/xml/introduction/

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();
Xml_Doc.LoadXml(Xml_File);
XmlNodeList Xml_Node_List = Xml_Doc.SelectNodes("Player_Stats");
Debug.Log(Xml_Node_List[3].InnerText);
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...

L.B L.B
Answer

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");
Comments