Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prepend a Stream?

I'm loading blobs out of a database as a byte array and I put them in a memory stream so that I can load them into an xmldocument for parsing.

However there are blobs that have multiple root nodes, this causes the parser to blow up.

My solution is to just make a new root node that encompasses the whole blob.

I can add onto the end just fine with a streamwriter however I can't figure out how to add onto the beginning.

How can I prepend to a stream?


Update
I was having too much trouble getting this to work. The "XML" I was extracting was not proper XML and I kept on having to add more and more regexes to remove bad XML before the XmlDocument Load. I ended up using the HtmlAgilityPack to parse out my valid sections of XML and I put those inside their own xml documents. Not the nicest solution but it works. Sigh

like image 720
Biff MaGriff Avatar asked Dec 28 '25 15:12

Biff MaGriff


2 Answers

Since you already have byte[] array from DB, writing more bytes before and after the array to memory stream should be easy:

// 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);
}

But since XmlDocument also provide LoadXml(str), I feel manipulating the string should be more straight forward solution:

// 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);
like image 62
Gant Avatar answered Dec 31 '25 06:12

Gant


You can't directly. This leads to two options:

  • write in an opening tag into the memorystream prior to loading the blobs
  • create a second memorystream, write in an opening tag, copy the first into the second...
like image 42
spender Avatar answered Dec 31 '25 07:12

spender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!