【发布时间】:2016-05-29 09:18:34
【问题描述】:
早上好, 我有一个以这种方式编写为 XML 文件的模板文件
<Simulation>
<Pedestrian Name="Mother">
<Initial_Position In_X="3" In_Y="3" />
<Final_Position>
<First Fin_X="6" Fin_Y="6" Time="2" />
</Final_Position>
</Pedestrian>
我实现了一个类来读取文件。
while (reader.Read() || i<Number_of_pedestrian)
{
if (reader.Name == "Pedestrian")
{
if (reader.HasAttributes == true)
{
name = reader.GetAttribute("Name");
//MessageBox.Show(name);
}
}
if(reader.Name == "Initial_Position")
{
if (reader.GetAttribute("In_X") != null && reader.GetAttribute("In_Y") != null)
{
X1 = int.Parse(reader.GetAttribute("In_X"));
Y1 = int.Parse(reader.GetAttribute("In_Y"));
}
}
if (reader.Name == "Initial_Position")
{
if (reader.GetAttribute("Fin_X") != null && reader.GetAttribute("Fin_Y") != null)
{
X2 = int.Parse(reader.GetAttribute("Fin_X"));
Y2 = int.Parse(reader.GetAttribute("Fin_Y"));
}
}
//Position Initial_Position = new Position (X1,Y1);
//Position Final_Position = new Position(X2, Y2);
Pd[i]=new Pedestrian (name, X1, Y1, X2, Y2);
Pd[i].Draw();
i++;
}
能够读取任何属性(在本例中为“Name”)但无法在节点内部读取然后获取属性(在本例中为“Initial_Position”,然后是“In_X”)。
此外,Pd[i]=new Pedestrian (name, X1, Y1, X2, Y2); 行给我以下错误:
System.IndexOutOfRangeException occurs.
Additional Information : index over limits of matrix
【问题讨论】:
-
Pedestrian类是什么? -
我建议您尝试某种 XML 反序列化或 LINQ to XML。基于
XmlDocument的解决方案往往更难使用。 -
代码中缺少一些信息。
Pedestrianclass 是什么,reader是什么类型(我假设是 XmlReader),Pd数组在哪里定义。另外,System.IndexOutOfRangeException可能是由于数组没有足够的空间造成的。
标签: c# xml visual-studio