从我的xml(de)序列化程序得到奇怪的结果

时间:2015-11-04 07:20:09

标签: c# xml xml-serialization xml-deserialization

我创建了一个streamExtension,我可以简单地将流序列化和反序列化到xml文件中,代码如下所示:

/// <summary>
/// Contains the logic for streaming extensions.
/// </summary>
public static class StreamExtensions
{
    /// <summary>
    /// Serialize an object.
    /// </summary>
    /// <typeparam name="T">The type of the object that gets serialized.</typeparam>
    /// <param name="stream">The stream to which the bytes will be written.</param>
    /// <param name="serializableObject">The object that gets serialized.</param>
    public static void SerializeObject<T>(this Stream stream, T serializableObject) where T : IXmlSerializable
    {
        var xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8);
        xmlTextWriter.Formatting = Formatting.Indented;
        xmlTextWriter.IndentChar = ' ';
        xmlTextWriter.Indentation = 4;

        var serializer = new XmlSerializer(typeof(T));

        serializer.Serialize(xmlTextWriter, serializableObject);

        xmlTextWriter.Close();
        stream.Close();
    }

    /// <summary>
    /// Deserialize a stream and return the object.
    /// </summary>
    /// <typeparam name="T">The type of the object that returns from the deserialization.</typeparam>
    /// <param name="stream">The stream which contains the bytes to deserialize.</param>
    /// <returns>The object recovered.</returns>
    public static T DeserializeObject<T>(this Stream stream)
    {
        var xmlTextReader = new XmlTextReader(stream);
        var serializer = new XmlSerializer(typeof(T));

        var result = (T)serializer.Deserialize(xmlTextReader);

        xmlTextReader.Close();
        stream.Close();

        return result;
    }
}

2非常简单(如果我可以这样说:优雅的)序列化和反序列化的方法。

我正在使用这个类作为测试:

/// <summary>
/// A serializable class for testing purposes.
/// </summary>
public class SerializableXmlTest : IXmlSerializable
{
    #region Fields
    private string mTestString = string.Empty;
    #endregion

    #region Properties
    /// <summary>
    /// Gets or sets the configuration for this simulation.
    /// </summary>
    /// <value>The configuration for this simulation.</value>
    public string TestString
    {
        get
        {
            return mTestString;
        }

        set
        {
            mTestString = value;
        }
    }
    #endregion

    #region XML serialization region
    /// <summary>
    /// Write the extra information to an XML stream.
    /// </summary>
    /// <param name="writer">Writer to write to.</param>
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteStartElement(MethodBase.GetCurrentMethod().DeclaringType.Name);
        writer.WriteAttributeString("TestString", this.TestString);
        writer.WriteEndElement();
    }

    /// <summary>
    /// Read the extra information from an XML stream.
    /// </summary>
    /// <param name="reader">Reader to read from.</param>
    public void ReadXml(XmlReader reader)
    {
        if ((reader.MoveToContent() == XmlNodeType.Element) && (reader.Name == MethodBase.GetCurrentMethod().DeclaringType.Name))
        {
            reader.Read();
            this.TestString = reader.GetAttribute("TestString");
        }

        reader.ReadEndElement();
    }

    /// <summary>
    /// This method is reserved when implementing the IXmlSerializable interface.
    /// </summary>
    /// <returns>An XmlSchema that describes the XML representation of the
    /// object that is produced by the WriteXml method and consumed by the
    /// ReadXml method.</returns>
    public XmlSchema GetSchema()
    {
        return null;
    }
    #endregion
}

这是我单元测试中的代码:

/// <summary>
/// Test the stream extension class for normal function.
/// </summary>
[Test]
public void TestStreamExtension()
{
    File.Delete(mFileName);
    var testObject = new SerializableXmlTest();
    testObject.TestString = "Test";

    Stream saveFileStream = new FileStream(mFileName, FileMode.OpenOrCreate);
    saveFileStream.SerializeObject(testObject);

    Stream openFileStream = new FileStream(mFileName, FileMode.OpenOrCreate);
    var testObjectClone = openFileStream.DeserializeObject<SerializableXmlTest>();
    Assert.IsTrue(testObject.TestString.Equals(testObjectClone.TestString));
    }

输出的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<SerializableXmlTest>
    <SerializableXmlTest TestString="Test" />
</SerializableXmlTest>

然而,有些事情我不明白,至少其中一件肯定是错的(我认为)

首先,我希望我的xml文件看起来像这样:

<?xml version="1.0" encoding="utf-8"?>
<SerializableXmlTest TestString="Test" />

但我可以理解你是否需要单独的开始和结束元素。

第二次尝试阅读它时,读者登陆的第一个元素是(正如预期的那样)<SerializableXmlTest>但是,如果我继续执行reader.Read()reader.ReadStartElement()调试器告诉我正在阅读:

{Whitespace, Value="\r\n    "}.

这是从哪里来的?为什么要读一个新的字符?显然,当我然后使用其他reader.Read()时,我会到达我的xml文件中的<SerializableXmlTest TestString="Test" />行。

我做错了什么?

P.S。 告诉你我更改了序列化和反序列化方法(它们曾经工作过)可能是明智的,但序列化只使用了xmlTextWriter而不是XmlSerializer。而Deserialize方法使用流阅读器而不是XmlTextReader。但为了试图让它们变得相同,我得到了这个我似乎无法解决的问题。

额外的问题:我是否应该使用XmlTextReader和writer?我也可以将我得到的流作为方法参数传递给序列化器不能吗?

1 个答案:

答案 0 :(得分:1)

一些事情。

1)序列化程序失败

XmlSerializer.Serialize(stream, object)

已经写入了文件和start元素的编码。这就是你获得奇怪输出的原因。减少WriteXML方法只打开流,然后让序列化程序完成剩下的工作。这将修复您编写的XML文件。

2)阅读\r\n

目前有两种方法可以在.NET中访问XML数据

  • XmlReader \ XmlWriter
  • XmlFile

当您使用XmlReader时,您将有更多访问XML文件的方式,并且更深入。另一方面,这意味着一些自动化会丢失。 XmlReader.Read()完全正确。首先,他找到一个<标志。所以现在他知道要读到>结束标记。然后你告诉他再读一遍。现在他读了一个\r\n的标志。现在他知道他必须停下来,因为你告诉他只读一个字符并且他没有找到<一个开始标记。

希望这有帮助