我有一个复杂的形状。应用程序允许绘制任何此形状的计数。 然后我必须将该图片保存为XML文件。如何将它们保存在XML文件中? 我的.xml已创建,但只有这样的信息。
<?xml version="1.0"?>
[Serializable, XmlRoot(Namespace = "http://www.intertech.com")]
public class ComplexShape
{
int x;
int y;
int a; // large elipse width/2
int b; // large elipse height/2
Form1 fr;
float angle;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveDlg = new SaveFileDialog())
{
// Configure the look and feel of the save dialog.
saveDlg.InitialDirectory = ".";
saveDlg.Filter = "XML Files|*.xml";
saveDlg.RestoreDirectory = true;
saveDlg.FileName = "MyShapes";
if (saveDlg.ShowDialog() == DialogResult.OK)
{
XmlSerializer xml_serializer = new XmlSerializer(typeof(ComplexShape));
using (Stream fstream = new FileStream(saveDlg.FileName, FileMode.Create, FileAccess.Write, FileShare.None))
{
xml_serializer.Serialize(fstream, complexShapes);
fstream.Close();
MessageBox.Show("serialized");
}
}
}
}
complexShapes是ComplexShapes的数组,它们在Button点击时创建和绘制。
答案 0 :(得分:2)
试试这个:
public class ComplexShape
{
int x;
int y;
int a; // large elipse width/2
int b; // large elipse height/2
Form1 fr;
float angle;
[XmlAttribute()]
public int X { get { return x; } set { x = value; } }
[XmlAttribute()]
public int Y { get { return y; } set { y = value; } }
[XmlAttribute()]
public int A { get { return a; } set { a = value; } }
[XmlAttribute()]
public int B { get { return b; } set { b = value; } }
[XmlIgnore()]
public Form1 Form { get { return fr; } }
[XmlAttribute()]
public float Angle { get { return angle; } set { angle = value; } }
}
public class Drawing
{
List<ComplexShape> shapes = new List<ComplexShape>();
[XmlIgnore()]
public List<ComplexShape> Shapes { get { return shapes; } }
[XmlArray("Shapes")]
public ComplexShape[] ShapesArray
{
get { return shapes.ToArray(); }
set { shapes = new List<ComplexShape>(value); }
}
public void Save(string fname)
{
XmlSerializer xml_serializer = new XmlSerializer(typeof(Drawing));
using (Stream fstream = new FileStream(fname, FileMode.Create, FileAccess.Write, FileShare.None))
{
xml_serializer.Serialize(fstream, this);
fstream.Close();
}
}
}
class Program
{
static void Main(string[] args)
{
Drawing dwg = new Drawing();
dwg.Shapes.Add(new ComplexShape());
dwg.Shapes.Add(new ComplexShape());
dwg.Shapes.Add(new ComplexShape());
dwg.Shapes.Add(new ComplexShape());
dwg.Save("ComplexShape.xml");
}
}
带输出:
<?xml version="1.0"?>
<Drawing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Shapes>
<ComplexShape X="0" Y="0" A="0" B="0" Angle="0" />
<ComplexShape X="0" Y="0" A="0" B="0" Angle="0" />
<ComplexShape X="0" Y="0" A="0" B="0" Angle="0" />
<ComplexShape X="0" Y="0" A="0" B="0" Angle="0" />
</Shapes>
</Drawing>