math-suite/Source/GraphingCalculator/IO/ExpressionFile.cs

89 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GraphingCalculator.IO
{
public class ExpressionFile
{
private List<VisualExpression> expressions = new List<VisualExpression>();
public List<VisualExpression> Expressions { get { return expressions; } }
public void SaveToFile(string filename)
{
System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(filename, new System.Xml.XmlWriterSettings() { Indent = true });
writer.WriteStartDocument();
writer.WriteStartElement("Document");
// Write expressions
writer.WriteStartElement("ExpressionList");
foreach (var i in Expressions)
{
writer.WriteStartElement("Expression");
writer.WriteAttributeString("String", i.ExpressionString);
writer.WriteAttributeString("IsVisible", i.IsVisible.ToString());
writer.WriteAttributeString("Color", i.Color.ToString());
foreach (var j in i.Variables)
{
writer.WriteStartElement("Variable");
writer.WriteAttributeString("Key", j.Key);
writer.WriteAttributeString("Value", j.Value.ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
}
writer.WriteEndElement();
// Finish
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
}
public void LoadFromFile(string filename)
{
System.Xml.XmlReader reader = System.Xml.XmlReader.Create(filename);
string varKey = "", varVal = "";
VisualExpression expr;
while (reader.Read())
switch (reader.NodeType)
{
case System.Xml.XmlNodeType.Element:
// Read an expression
if (reader.Name == "Expression")
{
expr = new VisualExpression();
while (reader.MoveToNextAttribute()) {
if (reader.Name == "String") expr.ExpressionString = reader.Value;
else if (reader.Name == "IsVisible") expr.IsVisible = bool.Parse(reader.Value);
else if (reader.Name == "Color") expr.Color = (System.Windows.Media.Color) System.Windows.Media.ColorConverter.ConvertFromString(reader.Value);
}
this.Expressions.Add(expr);
}
// A variable
else if (reader.Name == "Variable")
{
while (reader.MoveToNextAttribute()) {
if (reader.Name == "Key") varKey = reader.Value;
else if (reader.Name == "Value") varVal = reader.Value;
}
if (varKey != "")
this.Expressions.Last().Variables[varKey] = double.Parse(varVal);
}
break;
}
reader.Close();
}
}
}