【问题标题】:How do I prepend a Stream?如何添加流?
【发布时间】:2012-01-03 05:18:10
【问题描述】:

我将 blob 作为字节数组从数据库中加载出来,并将它们放入内存流中,以便将它们加载到 xmldocument 中进行解析。

但是有些 blob 有多个根节点,这会导致解析器崩溃。

我的解决方案是创建一个包含整个 blob 的新根节点。

我可以用 streamwriter 很好地添加到结尾,但是我不知道如何添加到开头。

如何预先添加到流中?


更新
我在让它工作时遇到了太多麻烦。我提取的“XML”不是正确的 XML,我不得不在加载 XmlDocument 之前添加越来越多的正则表达式来删除错误的 XML。我最终使用 HtmlAgilityPack 解析出我的有效 XML 部分,并将它们放入他们自己的 xml 文档中。不是最好的解决方案,但它有效。 叹息

【问题讨论】:

    标签: c# .net vb.net .net-3.5 stream


    【解决方案1】:

    由于您已经从 DB 中获得了 byte[] 数组,因此将数组前后的更多字节写入内存流应该很容易:

    // bytes from db
    byte[] multipleNodes = Encoding.UTF8.GetBytes("<first>..</first><second>..</second><third>..</third>");
    
    using (var ms = new MemoryStream())
    {
        // write opening tag
        byte[] newRoot = Encoding.UTF8.GetBytes("<newRoot>");
        ms.Write(newRoot, 0, newRoot.Length);
    
        ms.Write(multipleNodes, 0, multipleNodes.Length);
    
        // write opening tag
        byte[] closeNewRoot = Encoding.UTF8.GetBytes("</newRoot>");
        ms.Write(closeNewRoot, 0, closeNewRoot.Length);
    
        // reset cursor position before pass it to xmldoc
        ms.Position = 0;
    
        var xml = new XmlDocument();
        xml.Load(ms);
    
        Console.WriteLine(xml.InnerXml);
    }
    

    但由于XmlDocument也提供LoadXml(str),我觉得操纵字符串应该是更直接的解决方案:

    // bytes from db
    byte[] multipleNodes = Encoding.UTF8.GetBytes("<first>..</first><second>..</second><third>..</third>");
    
    string stringFromBlob = Encoding.UTF8.GetString(multipleNodes);
    string withRootNode = string.Format("<newRoot>{0}</newRoot>", stringFromBlob);
    
    var xml = new XmlDocument();
    xml.LoadXml(withRootNode);
    
    Console.WriteLine(xml.InnerXml);
    

    【讨论】:

    • 您的第一个解决方案是我想要建议的。你的第二个,虽然直截了当,但感觉效率太低,以至于我认为第一个不是过早的优化......
    • @zmbq 对此不确定,但由于 OP 已经将 byte[] 数组加载到内存中。我觉得将其转换为字符串(并将其与其他文本一起格式化)的额外成本不应该很高。
    【解决方案2】:

    你不能直接。这导致了两种选择:

    • 在加载 blob 之前将开始标签写入内存流
    • 创建第二个内存流,写入开始标签,将第一个复制到第二个...

    【讨论】:

    【解决方案3】:

    这是我用的:

    public class CompositeStream : FileStream
    {
        Stream[] childStreams;
        int currentStreamIndex = 0;
        Stream currentStream;
        public long totalStreamRead{get; private set;}
    
        public CompositeStream(string pre, FileStream s_file, string post)
            : base(s_file.SafeFileHandle, FileAccess.Read)
        {
            totalStreamRead = 0;
    
            MemoryStream s_pre = new MemoryStream();
            MemoryStream s_post = new MemoryStream();
    
            byte[] b_pre = Encoding.UTF8.GetBytes(pre);
            s_pre.Write(b_pre, 0, b_pre.Length);
            s_pre.Flush();
            s_pre.Seek(0, SeekOrigin.Begin);
    
            byte[] b_post = Encoding.UTF8.GetBytes(post);
            s_post.Write(b_post, 0, b_post.Length);
            s_post.Flush();
            s_post.Seek(0, SeekOrigin.Begin);
    
            childStreams = new Stream[] { s_pre, s_file, s_post };
    
            currentStream = childStreams[currentStreamIndex++];
        }
    
        public override int Read(byte[] buffer, int offset, int count)
        {
            int totalBytesRead = 0;
            while (count > 0)
            {
                // Read what we can from the current stream
                int numBytesRead = currentStream.Read(buffer, offset, count);
                totalBytesRead += numBytesRead;
                count -= numBytesRead;
                offset += numBytesRead;
    
                // If we haven't satisfied the read request, 
                // we have exhausted the current stream.
                // Move on to the next stream and loop around to read more data.
                if (count > 0)
                {
                    // If we run out of child streams to read from...
                    if (currentStreamIndex >= childStreams.Length)
                        break; //get out
    
                    currentStream.Close();
                    currentStream = childStreams[currentStreamIndex++];
                }
            }
            totalStreamRead += totalBytesRead;
            return totalBytesRead;
        }
    }
    

    【讨论】:

      【解决方案4】:

      一个干净的方法是实现一个CompositeStreamReader,它将接受多个流,然后按顺序读出它们。

      https://web.archive.org/web/20100721082808/http://blogs.msdn.com/b/paolos/archive/2010/04/08/how-to-boost-message-transformations-using-the-xslcompiledtransform-class-extended.aspx 有一个实现,您可以适应它,但您可以使用更简单的方法。

      【讨论】:

      • 链接已损坏。
      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 2016-06-19
      • 2018-04-27
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-11-10
      相关资源
      最近更新 更多