当前位置:编程学习 > C#/ASP.NET >>

对象序列化如何控制xml格式?

string Instance="";
MemoryStream stream = null;
            TextWriter writer = null;
 
                stream = new MemoryStream(); // read xml in memory
                writer = new StreamWriter(stream, Encoding.UTF8);

                // get serialise object
                //XmlSerializer serializer = new XmlSerializer(typeof(Emp),"");
                XmlSerializer serializer = new XmlSerializer(Instance.GetType());

                XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
                xsn.Add(string.Empty, string.Empty);

                serializer.Serialize(writer, Instance, xsn); // read object
                int count = (int)stream.Length; // saves object in memory stream
                byte[] arr = new byte[count];
                stream.Seek(0, SeekOrigin.Begin);
                // copy stream contents in byte array
                stream.Read(arr, 0, count);
                //UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
                UTF8Encoding utf = new UTF8Encoding();
                return utf.GetString(arr).Replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>", "").Trim();


上面的代码结果为"<string />",我想得到"<string></string>",如何实现?
当然string Instance="";是最简单的应用,实际使用会是复杂类.

问题的焦点在 序列化过程会使用最短的形式,如果"<string></string>"会表示为"<string />",而"<string />"有些系统识别不了,为了兼容这些垃圾系统,只能将就他们...

大家有办法吗?
           --------------------编程问答-------------------- 这个问题估计是无解的啦 --------------------编程问答-------------------- http://topic.csdn.net/u/20101007/09/0eed9542-d5b4-4856-aa25-02367e7dbfab.html --------------------编程问答-------------------- 序列化完成后 Replace 用 <string /> 替换成 <string></string> --------------------编程问答-------------------- 不怕麻烦的话 可以使用IXmlSerializable自定义序列化过程
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,