Search code examples
c#xmlmonogameselectsinglenode

C#/Monogame - Reading in Single Node from XML always returns NULL


Currently I am trying to randomly select a name from an XML list and print it in the Console. However, the node seems to always be null. My XML Looks like this:

<?xml version="1.0" encoding="utf-8"?>
<XnaContent xmlns:ns="Microsoft.Xna.Framework">
  <Asset Type="Object">

    <nameData>
      <firstName>
        <name>Charles</name>
        <name>David</name>
        <name>Bob</name>
        <name>John</name>
      </firstName>
    </nameData>


  </Asset>
</XnaContent>

And C#:

//create XML document 
XmlDocument doc = new XmlDocument();

//load in XML file to doc
doc.Load("Content/XML/Names.xml");

Random rand = new Random();
int count = 1;

//Set count to be the number of name nodes in the first name field
count = doc.SelectNodes("//firstName/name").Count;

//set randVal so it never exceeds amount of name nodes
int randVal = rand.Next(count);

// set objNode to the name at position()
XmlNode objNode = doc.SelectSingleNode("/nameData/firstName/name[position() = " + rand + "]");

//Write the randomly chosen name to console
Console.WriteLine(objNode.InnerText);

Thanks in advance for your help


Solution

  • 2 problems:

    1. you add the rand instead of the randVal to the XPath string
    2. you should start your XPath with // instead of / (just like you did in the Count

    Change from:

    objNode = doc.SelectSingleNode("/nameData/firstName/name[position() = " + rand + "]");
    

    To:

    objNode = doc.SelectSingleNode("//nameData/firstName/name[position() = " + randVal + "]");
    

    You can also remove the position() funtion and leave it like this:

    "//nameData/firstName/name[" + randVal + "]"