c++一个类需要有两种xml序列化形式怎么办

classa{public:stringname;chara[10];}将这个类用boost序列化为xml文件,第一次调用序列化时要求序列化name属性,第二次需要序列化... class a{
public:
string name;
char a[10];
}将这个类用boost序列化为xml文件,第一次调用序列化时要求序列化name属性,第二次需要序列化name和a[10],这该怎么办?
展开
 我来答
博飞港澳台联考
高粉答主

推荐于2016-10-04 · 说的都是干货,快来关注
知道大有可为答主
回答量:1.9万
采纳率:93%
帮助的人:1亿
展开全部
序列化或反序列化成一个字符串:方法一:序列化:public static string XMLSerialize<T(T entity){StringBuilder buffer = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextWriter writer = new StringWriter(buffer)){serializer.Serialize(writer, entity);}
return buffer.ToString();}反序列化:
public static T DeXMLSerialize<T(string xmlString){T cloneObject = default(T);
StringBuilder buffer = new StringBuilder();
buffer.Append(xmlString);
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StringReader(buffer.ToString())){Object obj = serializer.Deserialize(reader);
cloneObject = (T)obj;}
return cloneObject;}方法二:/// <summary
/// 对象序列化成 XML String
/// </summary
public static string XmlSerialize<T(T obj){string xmlString = string.Empty;
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream()){xmlSerializer.Serialize(ms, obj);
xmlString = Encoding.UTF8.GetString(ms.ToArray());}return xmlString;}
/// <summary
/// XML String 反序列化成对象
/// </summary
public static T XmlDeserialize<T(string xmlString){T t = default(T);
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (Stream xmlStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlString))){using (XmlReader xmlReader = XmlReader.Create(xmlStream)){Object obj = xmlSerializer.Deserialize(xmlReader);
t = (T)obj;}}return t;}如果要序列化到一个文件,则使用FileStream就可以了如:string strFile = @c:/book.xml;
using (FileStream fs = new FileStream(strFile, FileMode.Create)){
XmlSerializer formatter = new XmlSerializer(typeof(T));
formatter.Serialize(fs, entity);}附:其实还可以直接用SringWriter
StringBuilder sb = new StringBuilder();
System.IO.StringWriter writer = new System.IO.StringWriter(sb);
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式