首页 > 代码库 > WP8_读写XML

WP8_读写XML

/// <summary>
    /// WP手机,XML读写类
    /// </summary>
    public class WPXmlRW
    {
        /// <summary>
        /// 向WP手机,写入xml文件
        /// </summary>
        /// <param name="argStreamReader"></param>
        /// <param name="argFileName">写入的文件名</param>
        public void WriteToXml(StreamReader argStreamReader, string argFileName = "abc.xml")
        {
            //StreamReader sr = new StreamReader(stream123);//转化为可读流
 
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                //解析流 转化为XML
                XElement _xml = XElement.Parse(argStreamReader.ReadToEnd());
 
            XDocument doc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"), _xml);
 
                //创建一个本地存储的文件流
                IsolatedStorageFileStream location = new IsolatedStorageFileStream(argFileName ,
                        System.IO.FileMode.Create, storage);
 
                //将本地存储文件流转化为可写流
                System.IO.StreamWriter file = new System.IO.StreamWriter(location);
 
                //将XML文件 保存到流file上 即已经写入到手机本地存储文件上
                doc.Save(file);
 
                file.Dispose();
                location.Dispose();
            }
 
        }
 
        /// <summary>
        /// 从WP手机中,读xml文件
        /// </summary>
        /// <param name="argFileName"></param>
        /// <returns></returns>
        public XElement ReadFromXml(string argFileName = "abc.xml")
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                XElement _xml;//定义Linq的XML元素
                //打开本地存储文件
                IsolatedStorageFileStream location = new IsolatedStorageFileStream(argFileName, FileMode.Open, storage);
                //转化为可读流
                System.IO.StreamReader file = new System.IO.StreamReader(location);
                //解析流 转化为XML
                _xml = XElement.Parse(file.ReadToEnd());
 
                file.Dispose();
                location.Dispose();
 
                if (_xml.Name.LocalName != null)
                {
                    return _xml;
                }
            }
            return null;
        }
    }