ferday
ferday

Reputation: 197

Converting xml to string and back again produces 'root element error'

I'm converting an "unusual" xml to a string. I say unusual as i'm using the .NET ChartSerializer to save winforms chart state:

var xml = new XmlDocument();
using (MemoryStream ms = new MemoryStream())
{
    chart1.Serializer.Save(ms);
    xml.Load(ms);
}

if i convert to a string using

using (StringWriter sw = new StringWriter())
{
     using (XmlTextWriter txt = new XmlTextWriter(sw))
     {
         xml.WriteTo(txt);
         string str = sw.ToString();
         fuse.c1 = str;
     }
}

and save it to a file (i've tried JSON, txt, xml), then convert back using

var xml = new XmlDocument();
xml.LoadXml(fuse.c1);
using (MemoryStream ms = new MemoryStream())
{
    xml.Save(ms);
    chart1.Serializer.Load(ms);
}

i get an error root element is missing

i don't understand the error, as i'm simply converting to a string and back again using the same classes etc.

i'm not very familiar with xml, can anyone spot my misstep? I'm trying to save multiple winforms charts without an .xml file for each chart

sample xml:

<Chart Size="854, 215">
  <Series>
    <Series Name="Series1" Legend="Legend1" ChartArea="ChartArea1" Color="Orange" LegendText="% Change">
      <Points>
        <DataPoint YValues="10.3973534917773" />
        <DataPoint XValue="0.2" YValues="8.37818721941151" />
        <DataPoint XValue="0.4" YValues="5.57375277883594" />
**snip many more data points**
     </Points>
    </Series>
  </Series>      
  <ChartAreas>
    <ChartArea Name="ChartArea1">
    </ChartArea>
  </ChartAreas>
</Chart>

Upvotes: 0

Views: 634

Answers (1)

Charles Mager
Charles Mager

Reputation: 26213

You have the answer to your specific question in the comments - you need to rewind the stream.

But it's worth noting that there seems to be overloads that accept TextWriter and TextReader, so you can do what you're doing with much less ceremony.

To save, you can use a StringWriter:

using (var writer = new StringWriter())
{
    chart1.Serializer.Save(writer);
    fuse.c1 = writer.ToString();
}

And to load it back again, you can use a StringReader:

using (var reader = new StringReader(fuse.c1))
{
    chart1.Serializer.Load(reader);
}

Upvotes: 1

Related Questions