我想将xml反序列化为c#。 但我收到错误,无法修复它。
错误是:
"There is an error in XML document (1, 2)."
...
"<A xmlns=''> was not expected."
反序列化代码:
public static object XmlDeserializeFromString(string objectData, Type type)
{
var xmlAttributes = new XmlAttributes();
var xmlAttributeOverrides = new XmlAttributeOverrides();
xmlAttributes.Xmlns = false;
xmlAttributeOverrides.Add(typeof(A10), xmlAttributes);
var serializer = new XmlSerializer(type, xmlAttributeOverrides);
object result=null;
try
{
using (TextReader reader = new StringReader(objectData))
{
result = serializer.Deserialize(reader);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return result;
}
课程是:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "A-1.0", Namespace = "")]
[System.Xml.Serialization.XmlRootAttribute("A", Namespace = "", IsNullable = false)]
public class A10
{
private string versField;
private string typeField;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
[System.Xml.Serialization.XmlAttributeAttribute()]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
}
通过测试:
string xml = "<A vers=\"1.0\" type=\"pd\">";
A10 a = (A10) XmlDeserializeFromString(xml, typeof(A10));
该异常将在线投放:
result = serializer.Deserialize(reader);
为什么会这样?怎么解决这个问题?
答案 0 :(得分:4)