XML 序列化类型转换器 [英] XML Serialization Type Converter
本文介绍了XML 序列化类型转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Json 中我可以这样做:
In Json I can do this:
[JsonProperty("type")]
[JsonConverter(typeof(MyTpeConverter))]
public BoxType myType { get; set; }
.....
public class BoxTypeEnumConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
....
}
}
使用 XML 时也可以这样做吗?
Is this also possible when working with XML?
[XmlElement("isFolder")]
[XmlConvert()] // ???
public string IsFolder { get; set; }
我的 Xml 文件有例如
My Xml File has e.g.
....
<isFolder>t</isFolder>
....
我希望t"为真".
推荐答案
有两种方式:简单的方法::)
Threre are two ways: Simple way: :)
[XmlElement("isFolder")]
public string IsFolderStr { get; set; }
[XmlIgnore]
public bool IsFolder { get{ ... conversion logic from IsFolderStr is here... }}
第二种方法是创建一个处理自定义转换的类:
second way is to create a class that would handle custom convertion:
public class BoolHolder : IXmlSerializable
{
public bool Value { get; set }
public System.Xml.Schema.XmlSchema GetSchema() {
return null;
}
public void ReadXml(System.Xml.XmlReader reader) {
string str = reader.ReadString();
reader.ReadEndElement();
switch (str) {
case "t":
this.Value = true;
...
}
}
并用 BoolHolder 替换属性的定义:
and replace definition of the property with BoolHolder:
public BoolHolder IsFolder {get;set;}
public BoolHolder IsFolder {get;set;}
这篇关于XML 序列化类型转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文