Click here to Skip to main content
15,917,174 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello!

I am using MemoryStream and StringBuilder and I want to read the XML file using StreamReader/StreamWriter.

Please help.

Regards
Aman

What I have tried:

C#
XDocument xdoc = new XDocument();
string filecontent = PreProcessXML(lvi.Tag.ToString()); //XML File

using (MemoryStream ms = new MemoryStream())
{
  using (StreamWriter sw = new StreamWriter(ms))
{
  sw.Write(filecontent);
  using (StreamReader sr = new StreamReader(ms))
{
  sr.ReadToEnd();
  xdoc = XDocument.Load(sr); //System.Xml.XmlException: 'Root element is missing.' I am getting this error here during execution.
}
}
}


C#
//Custom Function to change a few tags in the original XML for input.

C#
private string PreProcessXML(String xmlpath)
{
  StringBuilder sb = new StringBuilder();

  string openbreak = "";
  string closebreak = "";

  foreach (var line in File.ReadLines(xmlpath))
{
  if (line.StartsWith("<break "))
{
  openbreak = line.Replace("/", "");

  if (closebreak != "")
{
  sb.AppendLine(closebreak);
}
  else
  closebreak = "</break>";

  sb.AppendLine(openbreak);
}
  else
{
  if (line == "</sec>")
{
  sb.AppendLine(closebreak);
  closebreak = "";
}
  sb.AppendLine(line);
}
}
  return sb.ToString();
}
Posted
Updated 30-Jan-19 0:36am
v3
Comments
Richard MacCutchan 30-Jan-19 12:41pm    
Why do you make things more complicated for yourself? Just feed the original file into the reader and you will not need all this extra processing.

1 solution

Look at your code:
sr.ReadToEnd();
xdoc = XDocument.Load(sr);
So the stream is at the end of the data, and you pass it to the XML processor? Rewind it, so it is at some data!
using (MemoryStream ms = new MemoryStream())
    {
    using (StreamWriter sw = new StreamWriter(ms))
        {
        sw.Write(filecontent);
        using (StreamReader sr = new StreamReader(ms))
            {
            sr.BaseStream.Seek(0, SeekOrigin.Begin);
            ...
            }
        }
    }
 
Share this answer
 
Comments
Primo Chalice 30-Jan-19 6:58am    
The solution solved that issue but generated another one. SO I used the following approach and it worked :)

byte[] myByteArray = System.Text.Encoding.UTF8.GetBytes(filecontent);
MemoryStream ms = new MemoryStream(myByteArray);
StreamReader sr = new StreamReader(ms);
xdoc = XDocument.Load(sr);
Primo Chalice 30-Jan-19 6:59am    
Also, please answer this question if you can. I really need a solution for this one:
https://www.codeproject.com/Questions/1275827/How-do-I-remove-the-child-nodes-but-still-keep-the

Regards

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900