Object 序列化为 Xml 文档

namespace XmlSerlize
{
    public sealed partial class MainPage : Page
    {

        public MainPage()
        {
            this.InitializeComponent();
        }

        async void Button_Click(object sender, RoutedEventArgs e)
        {
            TextBox_Input textstring = new TextBox_Input()
            {
                textInput = boxtext.Text,
                caluate = 99
            };

            StorageFolder localFolder = ApplicationData.Current.LocalCacheFolder;
            StorageFile logfile = await localFolder.CreateFileAsync("cmyxml.txt", CreationCollisionOption.OpenIfExists);

            XmlSerializer serializer = new XmlSerializer(typeof(TextBox_Input));
            var writer = new StringWriter();
            serializer.Serialize(writer, textstring);
            writer.Dispose();

            await FileIO.WriteTextAsync(logfile, writer.ToString());
            string textt = await FileIO.ReadTextAsync(logfile);
            boxtext.Text = textt + logfile.ToString();

        }
    }
    public class TextBox_Input
    {

        public string textInput = "123456789";
        public int caluate;
    }
}

 反序列化 Xml 文档

async void Button_Click_1(object sender, RoutedEventArgs e)
        {

            StorageFolder localFolder = ApplicationData.Current.LocalCacheFolder;
            StorageFile logfile = await localFolder.CreateFileAsync("cmyxml.xml", CreationCollisionOption.OpenIfExists);

            String reader= await FileIO.ReadTextAsync(logfile);

            byte[] byteArray = Encoding.Unicode.GetBytes(reader);  //byte[] byteArray = Encoding.ASCII.GetBytes(contents); 
            MemoryStream stream = new MemoryStream(byteArray);

            XmlSerializer serializer = new XmlSerializer(typeof(TextBox_Input));

            mybox = serializer.Deserialize(stream) as TextBox_Input;

            boxtext.Text = mybox.textInput;
     }

 

posted @ 2017-05-25 16:25  韵切  阅读(218)  评论(0编辑  收藏  举报