无法将类型为“System.Object[]”的对象强制转换为类型“System.Web.UI.WebControls.Xml”。
代码如下所示:
C# code
protected void btn_getStuMs_Click(object sender, EventArgs e)
{
Object[] ms = student.exec("张三", "18", "北大", "男");
Xml xml;
for (int i = 0; i < ms.Length; i++)
xml = (Xml)ms[i];
}
这行 xml = (Xml)ms[i];在类型转换时出错:无法将类型为“System.Object[]”的对象强制转换为类型“System.Web.UI.WebControls.Xml”。
跟踪ms变量结构:
-ms{object[1]}
-[0]{object[1]}
-[0]{System.Xml.XmlNode[6]}
+[0]{Attribute,Name="xsi:type",value="soa:Object"}
+[1]{Element,Name="soa:name"}
+[1]{Element,Name="soa:age"}
+[1]{Element,Name="soa:school"}
+[1]{Element,Name="soa:sex"}
+[1]{Element,Name="soa:count"}
请各位帮忙看看,谢谢!
------解决方案--------------------
for循环中写:
Response.Write(ms[i].GetType().Name+"<br/>");
看看输出的ms[i]的具体类型是什么?不是Xml的话当然是不能转换的。
------解决方案--------------------
protected void btn_getStuMs_Click(object sender, EventArgs e)
{
string[] ms = new string[] { "张三", "18", "北大", "男" };
string a= mArrayToXml(ms);
}
public string mArrayToXml(string[] mArray)
{
System.IO.TextWriter tw = default(System.IO.TextWriter);
tw = new System.IO.StringWriter();
XmlTextWriter writer = new XmlTextWriter(tw);
//Use indenting for readability.
writer.Formatting = Formatting.Indented;
//xml声明(Write the XML delcaration. )
writer.WriteStartDocument();
writer.WriteStartElement("marray");
for (int i = 0; i <= mArray.Length - 1; i++)
{
writer.WriteElementString("items", mArray[i]);
}
writer.WriteEndDocument();
writer.Flush();
writer.Close();
return tw.ToString();
}