目前我正在尝试从XML列表中随机选择一个名称并将其打印在控制台中。但是,节点似乎总是为空。我的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);
提前感谢您的帮助
答案 0 :(得分:1)
2个问题:
sc.hasNextDouble
而不是rand
添加到randVal
字符串XPath
代替XPath
开始//
(就像您在/
中所做的那样更改自:
Count
要:
objNode = doc.SelectSingleNode("/nameData/firstName/name[position() = " + rand + "]");
你也可以删除position()函数并保留如下:
objNode = doc.SelectSingleNode("//nameData/firstName/name[position() = " + randVal + "]");
答案 1 :(得分:0)
公会的答案向您展示了如何解决您的问题,但另一种选择是完全取消您对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)];