【问题标题】:Writing compact xml with XmlDictionaryWriter.CreateBinaryWriter and a XmlDictionary使用 XmlDictionaryWriter.CreateBinaryWriter 和 XmlDictionary 编写紧凑的 xml
【发布时间】:2016-02-08 13:59:17
【问题描述】:

我想以紧凑的格式将 xml 文档写入磁盘。为此,我使用了net框架方法XmlDictionaryWriter.CreateBinaryWriter(Stream stream,IXmlDictionary dictionary)

此方法编写一个自定义的紧凑二进制 xml 表示,以后可以由XmlDictionaryWriter.CreateBinaryReader 读取。该方法接受可以包含公共字符串的XmlDictionary,因此不必每次都在输出中打印这些字符串。字典索引将打印在文件中,而不是字符串。 CreateBinaryReader 以后可以使用同一个字典来反转这个过程。

但是我传递的字典显然没有使用。考虑这段代码:

using System.IO;
using System.Xml;
using System.Xml.Linq;

class Program
{
    public static void Main()
    {
        XmlDictionary dict = new XmlDictionary();
        dict.Add("myLongRoot");
        dict.Add("myLongAttribute");
        dict.Add("myLongValue");
        dict.Add("myLongChild");
        dict.Add("myLongText");

        XDocument xdoc = new XDocument();
        xdoc.Add(new XElement("myLongRoot",
                                new XAttribute("myLongAttribute", "myLongValue"),
                                new XElement("myLongChild", "myLongText"),
                                new XElement("myLongChild", "myLongText"),
                                new XElement("myLongChild", "myLongText")
                                ));

        using (Stream stream = File.Create("binaryXml.txt"))
        using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream, dict))
        {
            xdoc.WriteTo(writer);
        }
    }
}

产生的输出是这个(二进制控制字符未显示)

@
myLongRootmyLongAttribute˜myLongValue@myLongChild™
myLongText@myLongChild™
myLongText@myLongChild™
myLongText

显然 XmlDictionary 没有被使用。所有字符串都完整地出现在输出中,甚至多次出现。

这不是仅限于 XDocument 的问题。在上面的最小示例中,我使用 XDocument 来演示问题,但最初我在使用 XmlDictionaryWriter 和 DataContractSerializer 时偶然发现了这一点,因为它是常用的。结果是一样的:

[Serializable]
public class myLongChild
{
    public double myLongText = 0;
}
...
using (Stream stream = File.Create("binaryXml.txt"))
using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream, dict))
{
    var dcs = new DataContractSerializer(typeof(myLongChild));
    dcs.WriteObject(writer, new myLongChild());
}

结果输出没有使用我的 XmlDictionary。

如何让 XmlDictionaryWriter 使用提供的 XmlDictionary?

还是我误解了它的工作原理?

使用 DataContractSerializer 方法,我尝试调试网络框架代码(visual studio/options/debugging/enable net.framework source stepping)。显然,作家确实尝试在字典中查找上述每个字符串,正如预期的那样。但是,由于我不清楚的原因,line 356 of XmlbinaryWriter.cs 中的查找失败了。

我考虑过的替代方案:

  • XmlDictionaryWriter.CreatebinaryWriter 有一个重载,它也接受 XmlBinaryWriterSession。然后编写器将它遇到的任何新字符串添加到会话字典中。但是,我只想使用静态字典进行读写,这是事先知道的

  • 我可以将整个东西包装成一个GzipStream 并让压缩处理字符串的多个实例。但是,这不会压缩每个字符串的第一个实例,而且总体而言似乎是一种笨拙的解决方法。

【问题讨论】:

    标签: c# .net xml serialization binary-xml


    【解决方案1】:

    是的,有一个误解。 XmlDictionaryWriter 主要用于对象的序列化,它是XmlWriter 的子类。 XDocument.WriteTo(XmlWriter something)XmlWriter 作为参数。调用XmlDictionaryWriter.CreateBinaryWriter 将在内部创建System.Xml.XmlBinaryNodeWriter 的实例。这个类有两种“常规”写作的方法:

    // override of XmlWriter
    public override void WriteStartElement(string prefix, string localName)
    {
      // plain old "xml" for me please
    }
    

    对于基于字典的方法:

    // override of XmlDictionaryWriter
    public override void WriteStartElement(string prefix, XmlDictionaryString localName)
    {
      // I will use dictionary to hash element names to get shorter output
    }
    

    如果您通过DataContractSerializer 序列化对象,则主要使用后者(注意它的方法WriteObject 接受XmlDictionaryWriterXmlWriter 类型的参数),而XDocument 只接受XmlWriter

    至于你的问题 - 如果我是你,我会自己做XmlWriter

    class CustomXmlWriter : XmlWriter
    {
      private readonly XmlDictionaryWriter _writer;
      public CustomXmlWriter(XmlDictionaryWriter writer)
      {
        _writer = writer;
      }
      // override XmlWriter methods to use the dictionary-based approach instead
    }
    

    更新(根据您的评论)

    如果您确实使用了DataContractSerializer,那么您的代码中几乎没有错误。

    1) POC 类必须用[DataContract][DataMember] 属性修饰,序列化的值应该是属性而不是字段;还将命名空间设置为空值,否则您还必须处理字典中的命名空间。喜欢:

    namespace  XmlStuff {
      [DataContract(Namespace = "")]
      public class myLongChild
      {
        [DataMember]
        public double myLongText { get; set; }
      }
    
      [DataContract(Namespace = "")]
      public class myLongRoot
      {
        [DataMember]
        public IList<myLongChild> Items { get; set; }
      }
    }
    

    2) 也提供会话实例;对于空会话,字典编写器使用默认(XmlWriter-like)实现:

    // order matters - add new items only at the bottom
    static readonly string[] s_Terms = new string[]
    {
        "myLongRoot", "myLongChild", "myLongText", 
        "http://www.w3.org/2001/XMLSchema-instance", "Items"
    };
    
    public class CustomXmlBinaryWriterSession : XmlBinaryWriterSession
    {
      private bool m_Lock;
      public void Lock() { m_Lock = true; }
    
      public override bool TryAdd(XmlDictionaryString value, out int key)
      {
        if (m_Lock)
        {
          key = -1;
          return false;
        }
    
        return base.TryAdd(value, out key);
      }
    }
    
    static void InitializeWriter(out XmlDictionary dict, out XmlBinaryWriterSession session)
    {
      dict = new XmlDictionary();
      var result = new CustomXmlBinaryWriterSession();
      var key = 0;
      foreach(var term in s_Terms)
      {
        result.TryAdd(dict.Add(term), out key);
      }
      result.Lock();
      session = result;
    }
    
    static void InitializeReader(out XmlDictionary dict, out XmlBinaryReaderSession session)
    {
      dict = new XmlDictionary();
      var result = new XmlBinaryReaderSession();
      for (var i = 0; i < s_Terms.Length; i++)
      {
        result.Add(i, s_Terms[i]);
      }
      session = result;
    }
    
    static void Main(string[] args)
    {
      XmlDictionary dict;
      XmlBinaryWriterSession session;
      InitializeWriter(out dict, out session);
    
      var root = new myLongRoot { Items = new List<myLongChild>() };
      root.Items.Add(new myLongChild { myLongText = 24 });
      root.Items.Add(new myLongChild { myLongText = 25 });
      root.Items.Add(new myLongChild { myLongText = 27 });
    
      byte[] buffer;
      using (var stream = new MemoryStream())
      {
        using (var writer = XmlDictionaryWriter.CreateBinaryWriter(stream, dict, session))
        {
          var dcs = new DataContractSerializer(typeof(myLongRoot));
          dcs.WriteObject(writer, root);
        }
        buffer = stream.ToArray();
      }
    
    
      XmlBinaryReaderSession readerSession;
      InitializeReader(out dict, out readerSession);
      using (var stream = new MemoryStream(buffer, false))
      {
        using (var reader = XmlDictionaryReader.CreateBinaryReader(stream, dict, new XmlDictionaryReaderQuotas(), readerSession))
        {
          var dcs = new DataContractSerializer(typeof(myLongRoot));
          var rootCopy = dcs.ReadObject(reader);
        }
      }
    }    
    

    【讨论】:

    • 在切换到 XDocument 之前,我实际上使用 DataContractSerializer 进行了尝试;我只是将其排除在最小示例之外,因为结果完全相同: with var dcs = new DataContractSerializer(typeof(MyLongClass)); dcs.WriteObject(writer, new MyLongclass());不使用字典。调试显示,调用了 XmlBinaryNodeWriter 的基于字典的方法,Writer 试图在字典中查找值;但是由于某种原因,此查找失败。
    • 感谢您的帮助!关于[DataContract] 属性,我想你在这里弄错了; DatacontractSerializer 实际上可以序列化类,即使它们只有[Serializable] 属性,在这种情况下它也会序列化私有字段。参见例如stackoverflow.com/a/3156546/145999
    • 关于XmlBinaryWriterSession,是的,如果我使用其中之一,输出将不包含任何字符串。但这与这些字符串是否在字典中无关!即使使用空字典,DataContractSerializer 也只会动态填充会话字典。这意味着我以后不能在没有最终会话字典的情况下反序列化数据,这使得这种方法对我不起作用。 (参考我问题的倒数第二段)
    • 我真正想要的是一种让 XmlDictionaryWriter 和 Reader 只使用我的硬编码字典而不生成动态字典的方法。现在这可能是不可能的;正如你所说,没有会话 XmlBinaryWriter 似乎无法正常工作。但是我在文档中找不到任何会阻止它工作的内容,并且没有会话但带有 dict 的 CreateBinaryWriter() 调用在其他情况下似乎毫无用处。
    • @HugoRune - 虽然我已经概述了它:) 我已经更新了我的代码示例以包含读取部分。
    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多