我有一个标记为Serializable的类,它有一个Uri属性。我怎样才能让Uri序列化/反序列化而不使用string类型的属性呢?
发布于 2013-01-18 05:25:57
基于how to serialize TimeSpan
的一个答案,我最终得到了这个,它对我来说工作得很好,并且不需要额外的属性:
public class XmlUri : IXmlSerializable
{
private Uri _Value;
public XmlUri() { }
public XmlUri(Uri source) { _Value = source; }
public static implicit operator Uri(XmlUri o)
{
return o == null ? null : o._Value;
}
public static implicit operator XmlUri(Uri o)
{
return o == null ? null : new XmlUri(o);
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
_Value = new Uri(reader.ReadElementContentAsString());
}
public void WriteXml(XmlWriter writer)
{
writer.WriteValue(_Value.ToString());
}
}
然后你可以像这样使用它
public class Settings
{
public XmlUri Uri { get; set; }
}
...
var s = new Settings { Uri = new Uri("http://www.example.com") };
它将很好地序列化和反序列化。
注意:不能使用上面链接问题中另一个答案中给出的XmlElement(Type = typeof(...))
属性的技巧,因为XmlSerializer
首先在原始类型上检查空的默认构造函数。
发布于 2009-06-24 06:56:36
使用xml serializer,您会受到限制--它不像(比方说)一些二进制格式化程序/ISerializable
选项那么通用。一个常见的技巧是拥有用于序列化的第二个属性:
[XmlIgnore]
public Uri Uri {get;set;}
[XmlAttribute("uri")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public string UriString {
get {return Uri == null ? null : Uri.ToString();}
set {Uri = value == null ? null : new Uri(value);}
}
两个可浏览属性将其隐藏在视图之外(但它需要在公共API上才能让XmlSerializer
使用它)。XmlIgnore
告诉它不要尝试Uri
;而[XmlAttribute(...)]
(或[XmlElement(...)]
)告诉它在(反)序列化UriString
时重命名它。
(请注意,EditorBrowsable
仅适用于声明该类型的程序集外部的代码)
发布于 2015-12-02 18:17:21
对于发现这个问题的其他人和不喜欢解决方案的人来说,还有另一个更灵活、更强大的解决方案。它的实现是IXmlSerializable接口。这比较困难,但这是值得的。您可以创建任何您想要的xml。最简单的例子是:
public class Product : IXmlSerializable
{
public string Code { get; set; }
public string Model { get; set; }
public string Name { get; set; }
public Uri ImageUri { get; set; }
public virtual System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public virtual void ReadXml(XmlReader reader)
{
reader.MoveToContent();
Code = reader.GetAttribute("Code");
Model = reader.GetAttribute("Model");
Name = reader.GetAttribute("Name");
if (reader.ReadToDescendant("Image") && reader.HasAttributes)
ImageUri = new Uri(reader.GetAttribute("Src"));
}
public virtual void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("Code", Code);
writer.WriteAttributeString("Model", Model);
writer.WriteAttributeString("Name", Name);
if (ImageUri != null)
{
writer.WriteStartElement("Image");
writer.WriteAttributeString("Src", ImageUri.AbsoluteUri);
writer.WriteEndElement();
}
}
}
在xml中你会得到类似这样的东西:
<PriceContainer Code="314" Model="PP500" Name="NuTone PurePower PP500 Power Unit">
<Image Src="http://www.thinkvacuums.com/images/nutone-pp500-activac.jpg" />
</PriceContainer>
https://stackoverflow.com/questions/1036492
复制相似问题