大家好 我曾尝试编写一个简单的 xml 阅读器,但发现它无意中跳过了 xml 文件中的所有其他元素。
我猜我是在告诉它两次移动到下一个元素,但我不确定发生了什么或解决方案是什么。
任何帮助将不胜感激:)
这里是代码示例和xml文件示例
public LevelLoader(string theLevelFile ,ContentManager theContent)
{
XmlTextReader reader = new XmlTextReader(theLevelFile);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "tilerow":
{
currentRow = currentRow + 1;
Console.WriteLine("row found");
currentCol = 0;
break;
}
case "tilecol":
{
Console.WriteLine("col found");
currentTexture = reader.ReadElementContentAsFloat();
currentCol = currentCol + 1;
break;
}
}
}
}
}
示例 xml
<tilerow>
<tilecol>1</tilecol><tilecol>2</tilecol><tilecol>3</tilecol><tilecol>4</tilecol><tilecol>5</tilecol><tilecol>6</tilecol><tilecol>7</tilecol><tilecol>8</tilecol><tilecol>9</tilecol><tilecol>10</tilecol>
</tilerow>
最佳答案
Read() 方法将首先返回 Column 元素,然后是 Column“Text”,然后是 EndElement。当您使用 ReadElementContentAsFloat 时,它会读取当前内容,然后将下一个 Read() 定位到下一个“文本”部分。由于您的循环跳过了 Text 和 EndElement,因此它错过了 2、4、...
试试这个...
case "tilecol":
{
Console.WriteLine("col found");
reader.Read();
float.TryParse(reader.Value, out currentTexture);
currentCol = currentCol + 1;
break;
}
关于c# 简单的 xml 阅读器跳过所有其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4117757/