C#XML序列化问题
【腾讯云】亏本大甩卖,服务器4核16G 1年370元(带宽12M,系统盘120GB SSD盘,月流量2000GB)!!!!!!
云产品 配置 价格
服务器 1核2G,带宽5M,系统盘50GB SSD盘,月流量500GB 38元/年
MySQL 1核1G 19元/年
服务器 16核32G,带宽18M,系统盘250GB SSD盘,月流量5000GB 1197元/年
点我进入腾讯云,查看更多详情

I have created a method that accepts an object then attempts to serialize the object to Xml by first using the XmlSerializer to serialize to a string, then load the Xml back into an XmlDocument object for the method to return. The code looks like this;

 public static XmlDocument ConvertObjectToXMLMessage(object ObjectToConvert)
    {
        MemoryStream stream = null;
        XmlWriter writer = null;
        XmlSerializer serializer = null;
        XmlDocument xmlDoc = new XmlDocument();
        UnicodeEncoding utf = new UnicodeEncoding();
        UTF8Encoding utf8 = new UTF8Encoding();
        ASCIIEncoding ascii = new ASCIIEncoding();
        string result = string.Empty;

        try
        {
            stream = new MemoryStream();
            //writer = new StreamWriter(stream, Encoding.Unicode);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Encoding = Encoding.UTF8;
            writer = XmlWriter.Create(stream, settings);                

            serializer = new XmlSerializer(ObjectToConvert.GetType());
            serializer.Serialize(writer, ObjectToConvert);

            int count = Convert.ToInt32(stream.Length);
            Byte[] arr = new Byte[count];

            stream.Seek(0, SeekOrigin.Begin);

            stream.Read(arr, 0, count);

            result = utf8.GetString(arr).Trim();

            // if this is being used during a debug session, the xml will be written to the Debug Console
#if DEBUG
            //blank line before
            Debug.WriteLine(string.Empty);
            // output result
            Debug.Write(result);
            //blank line after
            Debug.WriteLine(string.Empty);
#endif

            xmlDoc.LoadXml(result);

            return xmlDoc;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (writer != null)
                writer.Close();
        }
    }

All works well until the xmlDoc.LoadXml(result) command. This throws an exception; {"Data at the root level is invalid. Line 1, position 1."}

As you can see, I have declared a number of encoding variables. If I use the ASCII encoding, it works. I need to use UTF8.

Any ideas why this does not work? I think it is because of spurious characters being inserted at the start of the Xml ofter serialisation. How do I avoid this? The types of classes that I could be serializing would be entity framework objects or proxy classed generated from XSD's or WSDL.

#0

What if you load the stream directly without manually reading it or converting it?

XmlDocument xd = new XmlDocument();
xd.Load( stream );

This will at least reduce the number of places an error could be occurring.

#1

The code seems to be just fine... are you opening with an editor before trying to access your file by code?

I got that problem with an editor that was adding some stuff in my file

推荐文章

Wordpress页眉和页脚到PHP站点

Wordpress页眉和页脚到PHP站点

推荐文章

使用多级委托或lambdas生成LINQ查询时出现异常(“值不能为空。参数名称:实例“)

使用多级委托或lambdas生成LINQ查询时出现异常(“值不能为空。参数名称:实例“)

推荐文章

将嵌入的html文件加载到webrowser控件中,并替换img标记以指向嵌入的图像

将嵌入的html文件加载到webrowser控件中,并替换img标记以指向嵌入的图像

推荐文章

Unix中的TCP套接字-通知服务器我已完成发送

Unix中的TCP套接字-通知服务器我已完成发送

推荐文章

jQuery图像库和Ajax回调以加载其他图像

jQuery图像库和Ajax回调以加载其他图像

推荐文章

如何在多个视图中滚动?

如何在多个视图中滚动?

推荐文章

Python函数返回jQuery var

Python函数返回jQuery var

推荐文章

我的重新验证php有什么问题?

我的重新验证php有什么问题?

推荐文章

wpf中的样式和触发器

wpf中的样式和触发器

推荐文章

Linq结果到IEnumerable无效强制转换

Linq结果到IEnumerable无效强制转换

推荐文章

在Cocoa中使用表作为布局容器?

在Cocoa中使用表作为布局容器?

推荐文章

firefox的javascript和windows与mac的chrome兼容性

firefox的javascript和windows与mac的chrome兼容性

推荐文章

用于日志记录的EJB3拦截器

用于日志记录的EJB3拦截器

推荐文章

MySQL中随时间的增减趋势计算

MySQL中随时间的增减趋势计算

推荐文章

我可以在COM对象服务器URL上指定端口吗?

我可以在COM对象服务器URL上指定端口吗?

推荐文章

URI的任何路径段都可以有查询组件吗?

URI的任何路径段都可以有查询组件吗?