[英]How ignore read only property set during XmlSerializer deserialization?
I have read only property in my class 我班上只有只读属性
[XmlIgnore]
public string Amount
{
get { return "Some value"; }
}
When I try deserialize object from file I don't want that deserialization goes throw exception and I don't receive object. 当我尝试从文件中反序列化对象时,我不希望反序列化会引发异常,并且我不会接收对象。 I tried use xml ignore attribute but it is not help me.
我尝试使用xmlignore属性,但这对我没有帮助。 Only what I need to set properties which is exist in my file.
只有我需要设置文件中存在的属性。
XML file XML文件
<?xml version="1.0" encoding="utf-8"?>
<Class xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Id>1</KaumeheId>
<PrivaatKey>123</PrivaatKey>
</Class>
Class 类
public class Class
{
public int Id { get; set; }
public string PrivaatKey { get; set; }
public string Amount
{
get { return "Some value"; }
}
}
Serializer 串行
public static class XmlDeserializerService<T>
{
public static void LoadDataToClass(T obj, string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
obj = (T) serializer.Deserialize(fileStream);
}
}
}
Additional info(modified): 附加信息(已修改):
If I look in debugger under obj.Amount I have Amount = 'obj.Amount' threw an exception of type System.NullReferenceException
如果我在obj.Amount下的调试器中查看,则我有Amount ='obj.Amount'引发了
System.NullReferenceException
类型的异常
I think the problem is in your deserialization method, i would change it to return object: 我认为问题出在您的反序列化方法中,我将其更改为返回对象:
public static class XmlDeserializerService<T>
{
public static T LoadDataToClass(string filePath)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
return (T)serializer.Deserialize(fileStream);
}
}
}
My Class is : 我的课程是:
public class Class
{
public int Id { get; set; }
public string PrivaatKey { get; set; }
public string Amount
{
get { return "Some value"; }
}
}
If i use it after that : 如果我在那之后使用它:
var r = XmlDeserializerService<Class>.LoadDataToClass(@"yourxml");
I see all fields: 我看到所有字段:
That works, if you will have a valid xml, one that you have provided has invalid Id tag. 可行,如果您拥有有效的xml,则您提供的XML具有无效的ID标记。 Valid one is:
有效的是:
<?xml version="1.0" encoding="utf-8"?>
<Class xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Id>1</Id>
<PrivaatKey>123</PrivaatKey>
</Class>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.