版本:protobuf-net r282
对XElement对象进行序列化和反序列化,会导致NextNode、Parent等关系信息丢失。看起来里面只存储了Xml数据。
有没有办法存储关系信息?
谢谢!
这是我用来测试的一个类:
[ProtoContract]
public class Person
{
[ProtoMember(1)]
public string FirstName { get; set; }
[ProtoMember(2)]
public string FamilyName { get; set; }
[ProtoMember(3)]
public int Age { get; set; }
[ProtoMember(4)]
public XDocument Details { get; set; }
[ProtoMember(5)]
public XElement Business { get; set; }
// ctor
public Person() { } // ctor for Deserialize
public Person(string first, string family, int age, XDocument details)
{
FirstName = first;
FamilyName = family;
Age = age;
Details = details;
Business = Details == null ? null : Details.Descendants("business").FirstOrDefault();
}
// calculated properties
public string FullName { get { return FirstName + " " + FamilyName; } }
// Methods
public string GetDetails(string key)
{
if (this.Details == null) return null;
var found = (from n in Details.Descendants(key)
select n.Value).FirstOrDefault();
return found;
}
}
[更新]
避免该问题的一种方法是序列化 xelement 的绝对路径而不是其自身。这是一个示例。
using System.Xml.XPath;
.....
//[ProtoMember(5)]
public XElement Business { get; set; }
[ProtoMember(5)]
public string BusinessSerialized
{
get { return Business == null ? null : Business.GetAbsoluteXPath(); }
set
{
if (value == null) { Business = null; }
else
{
Business = Details.XPathSelectElements(value).FirstOrDefault();
}
}
}
GetAbsoluteXPath是 XElement 的扩展方法。我在这个问题中找到了它。