我有從Canvas類繼承的序列化的問題。我正在尋找更長時間的解決方案。我試過XMLSerializer,XAMLWriter現在試圖使用DataContractSerializer。從Canvas類繼承的序列化類
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Rectangle rectangle = new Rectangle();
rectangle.Width = 20;
rectangle.Height = 30;
Polyline polyLine = new Polyline();
PointCollection pointCollection = new PointCollection(){new Point(10,10), new Point(30,30), new Point(50,10)};
polyLine.Points = pointCollection;
NewCanvas newCanvas = new NewCanvas("test", rectangle, polyLine);
newCanvas.Width = 120;
newCanvas.Height = 150;
newCanvas.SaveToXML(@"Save.xml");
}
}
[Serializable]
public class NewCanvas : Canvas, ISerializable
{
private string _name;
private Rectangle _rectangle;
private Polyline _polyLine;
public NewCanvas(string name, Rectangle rectangle, Polyline polyLine)
{
_name = name;
_rectangle = rectangle;
_polyLine = polyLine;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("BaseProperties", XamlWriter.Save(this));
info.AddValue("Name", _name);
info.AddValue("Rectangle", XamlWriter.Save(_rectangle));
info.AddValue("PolyLine", XamlWriter.Save(_polyLine));
}
public NewCanvas(SerializationInfo info, StreamingContext context)
{
//Deserialization implement
}
public void SaveToXML(string fileName)
{
DataContractSerializer ser = new DataContractSerializer(typeof(NewCanvas));
XmlWriterSettings settings = new XmlWriterSettings() { Indent = true };
using (XmlWriter writer = XmlWriter.Create(fileName, settings))
{
ser.WriteObject(writer, this);
writer.Close();
}
}
}
上面的代碼生成:
<?xml version="1.0" encoding="utf-8"?>
<NewCanvas xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.datacontract.org/2004/07/Serializacja">
<BaseProperties i:type="x:string" xmlns=""><NewCanvas Width="120" Height="150" xmlns="clr-namespace:Serializacja;assembly=Serializacja" xmlns:av="http://schemas.microsoft.com/winfx/2006/xaml/presentation" /></BaseProperties>
<Name i:type="x:string" xmlns="">test</Name>
<Rectangle i:type="x:string" xmlns=""><Rectangle Width="20" Height="30" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" /></Rectangle>
<PolyLine i:type="x:string" xmlns=""><Polyline Points="10,10 30,30 50,10" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" /></PolyLine>
</NewCanvas>
我想是這樣的,如果沒有這些redudant命名空間xlmns=""
和和無需反覆<Rectangle ...>Rectangle ...</Rectangle>
<?xml version="1.0" encoding="utf-8"?>
<NewCanvas>
<BaseProperties Width="120" Height="150"/>
<Name>test</Name>
<Rectangle Width="20" Height="30"/>
<Polyline Points="10,10 30,30 50,10"/>
</NewCanvas>
你有什麼想法如何我可以做到這一點?