简体   繁体   English

.Net DataContractSerializer的往返XML序列化失败

[英]Round trip XML serializing with .Net DataContractSerializer fails

I seem to be getting some junk at the head of my serialized XML string. 我的序列化XML字符串的开头似乎有些破烂。 I have a simple extension method 我有一个简单的扩展方法

    public static string ToXML(this object This)
    {
        DataContractSerializer ser = new DataContractSerializer(This.GetType());


        var settings = new XmlWriterSettings { Indent = true };

        using (MemoryStream ms = new MemoryStream())
        using (var w = XmlWriter.Create(ms, settings))
        {
            ser.WriteObject(w, This);
            w.Flush();
            return UTF8Encoding.Default.GetString(ms.ToArray());
        }
    }

and when I apply it to my object I get the string 当我将其应用于对象时,我得到了字符串

<?xml version="1.0" encoding="utf-8"?>
<RootModelType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WeinCad.Data">
  <MoineauPump xmlns:d2p1="http://schemas.datacontract.org/2004/07/Weingartner.Numerics">
    <d2p1:Rotor>
      <d2p1:Equidistance>0.0025</d2p1:Equidistance>
      <d2p1:Lobes>2</d2p1:Lobes>
      <d2p1:MajorRadius>0.04</d2p1:MajorRadius>
      <d2p1:MinorRadius>0.03</d2p1:MinorRadius>
    </d2p1:Rotor>
  </MoineauPump>
</RootModelType>

Note the junk at the beginning. 请注意开头的垃圾。 When I try to deserialize this I get an error. 当我尝试反序列化时,出现错误。 If I copy paste the XML into my source minus the junk prefix I can deserialize it. 如果我将XML粘贴到源代码中(减去垃圾字首),则可以反序列化。 What is the junk text and how can I remove it or handle it? 什么是垃圾文字,如何删除或处理?

Note my deserialization code is 注意我的反序列化代码是

public static RootModelType Load(Stream data)
{
    DataContractSerializer ser = new DataContractSerializer(typeof(RootModelType));
    return (RootModelType)ser.ReadObject(data);
}

public static RootModelType Load(string data)
{
    using(var stream = new MemoryStream(Encoding.UTF8.GetBytes(data))){
        return Load(stream);
    }
}

This fix seems to work 此修复程序似乎有效

    public static string ToXML(this object obj)
    {
        var settings = new XmlWriterSettings { Indent = true };

        using (MemoryStream memoryStream = new MemoryStream())
        using (StreamReader reader = new StreamReader(memoryStream))
        using(XmlWriter writer = XmlWriter.Create(memoryStream, settings))
        {
            DataContractSerializer serializer = 
              new DataContractSerializer(obj.GetType());
            serializer.WriteObject(writer, obj);
            writer.Flush();
            memoryStream.Position = 0;
            return reader.ReadToEnd();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM