C#/Monogame - 从 XML 读取单个节点总是 returns NULL

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

目前我正在尝试从 XML 列表中随机 select 一个名称并将其打印在控制台中。但是,该节点似乎始终为空。我的 XML 看起来像这样:

<?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>

和 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);

在此先感谢您的帮助

2 个问题:

  1. 您将 rand 而不是 randVal 添加到 XPath 字符串
  2. 你应该用 // 开始你的 XPath 而不是 / (就像你在 Count

更改自:

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

收件人:

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

您也可以删除 position() 函数并保留它:

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

Guild 的回答向您展示了如何解决您的问题,但另一种选择是完全消除您对 XPath 的依赖:

var doc = XDocument.Load("Content/XML/Names.xml");

var names = doc.Descendants("name")
    .Select(x => x.Value)
    .ToList();

var rand = new Random();

var name = names[rand.Next(names.Count)];