Azure表存储:TableContinuationToken的Xml序列化

时间:2013-11-14 08:02:04

标签: azure xml-serialization azure-table-storage

我正在使用Microsoft.WindowsAzure.Storage v2.1.0.3。

尝试将 TableContinuationToken 序列化为XML。

序列化代码是:

String tokenXml;
var serializer = new XmlSerializer(typeof(TableContinuationToken));
using (var writer = new StringWriter())
{
  var writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true, NewLineChars = String.Empty };
  using (var xmlWriter = XmlWriter.Create(writer, writerSettings))
  {
    serializer.Serialize(xmlWriter, token);
  }
  tokenXml = writer.ToString();
}

反序列化代码是:

TableContinuationToken token; 
var serializer = new XmlSerializer(typeof(TableContinuationToken));
using (var stringReader = new StringReader(tokenXml))
{
  token = (TableContinuationToken)serializer.Deserialize(stringReader);
}

很简单。但是当我在异常发生后尝试反序列化令牌时:

System.InvalidOperationException : There is an error in XML document (1, 26).
----> System.Xml.XmlException : Unexpected Element 'ContinuationToken'

从序列化令牌代码中删除标签后工作正常!

可能是Microsoft.WindowsAzure.Storage v2.1.0.3中的BUG? 或者我做错了什么?

感谢。

1 个答案:

答案 0 :(得分:2)

我刚刚遇到过这个问题。您必须在TableContinuationToken实例上使用 WriteXml() ReadXml()方法,而不是使用自己的XmlSerializer实例。

    public static string SerializeToken(TableContinuationToken token)
    {
        string serialized = null;
        if (token != null)
        {
            using (var writer = new StringWriter())
            {
                using (var xmlWriter = XmlWriter.Create(writer))
                {
                    token.WriteXml(xmlWriter);
                }
                serialized = writer.ToString();
            }
        }

        return serialized;
    }

    public static TableContinuationToken DeserializeToken(string token)
    {
        TableContinuationToken contToken = null;
        if (!string.IsNullOrWhiteSpace(token))
        {
            using (var stringReader = new StringReader(token))
            {
                contToken = new TableContinuationToken();
                using (var xmlReader = XmlReader.Create(stringReader))
                {
                    contToken.ReadXml(xmlReader);
                }
            }
        }

        return contToken;
    }

我认为这是因为类和属性的序列化属性,但我还没有验证。我只知道提供的代码是解决方案。