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
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);
You can't directly. This leads to two options:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With