您的位置:首页 > 其它

WP8_读写XML WP8数据存储--独立存储文件

2014-09-01 16:10 513 查看
WP8数据存储--独立存储文件

主要的三个步骤

1.调用手机的独立存储

  例如:IsolatedStorageFilestorage=IsolatedStorageFile.GetUserStoreForApplication()

2.创建独立存储文件流

  例如:IsolatedStorageFileStreamlocation=newIsolatedStorageFileStream(nateText.Text+".item",System.IO.FileMode.Create,storage);

3.读写该文件流

  例如:将独立存储文件流转化为可写流

      System.IO.StreamWriterfile=newSystem.IO.StreamWriter(location);

    将XML文件保存到流file上,即已经写入到手机独立存储文件上,_doc是用户创建的文件:

      _doc.Save(file);

    转化为可读流:

      System.IO.StreamReaderfile=newSystem.IO.StreamReader(location);

    解析流,转化为XML

      _xml=XElement.Parse(file.ReadToEnd());

下面给出一个购物清单的例子

清单列表界面:





<Gridx:Name="LayoutRoot"Background="Transparent">
<Grid.RowDefinitions>
<RowDefinitionHeight="Auto"/>
<RowDefinitionHeight="*"/>
</Grid.RowDefinitions>

<!--TitlePanel包含应用程序的名称和页标题-->
<StackPanelGrid.Row="0"Margin="12,17,0,28">
<TextBlockText="我的应用程序"Style="{StaticResourcePhoneTextNormalStyle}"/>
<TextBlockText="购物清单"Margin="9,-7,0,0"Style="{StaticResourcePhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel-在此处放置其他内容-->
<Gridx:Name="ContentPanel"Grid.Row="1"Margin="12,0,12,0">
<ListBoxMargin="0,0,38,131"Name="Files"/>
<ButtonContent="添加"Name="btn_add"HorizontalAlignment="Left"Height="104"Margin="11,493,0,0"VerticalAlignment="Top"Width="243"/>
</Grid>
</Grid>


ViewCode





usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Navigation;
usingMicrosoft.Phone.Controls;
usingMicrosoft.Phone.Shell;
usingSystem.IO.IsolatedStorage;

namespacePhoneApp1
{
publicpartialclassIsoFiles:PhoneApplicationPage
{
publicIsoFiles()
{
InitializeComponent();
BindList();
btn_add.Click+=btn_add_Click;
}

voidbtn_add_Click(objectsender,RoutedEventArgse)
{
NavigationService.Navigate(newUri("/IsoFileAdd.xaml",UriKind.Relative));
}

privatevoidBindList()
{
Files.Items.Clear();//先清空一下ListBox数据
//获取应用程序的独立存储文件
using(IsolatedStorageFilestorage=IsolatedStorageFile.GetUserStoreForApplication())
{
//获取并循环*.item的存储文件
foreach(stringfilenameinstorage.GetFileNames("*.item"))
{
//动态构建一个Grid
Gridgrid=newGrid();
//定义第一列
ColumnDefinitionco1=newColumnDefinition();
GridLengthgl=newGridLength(200);
co1.Width=gl;
grid.ColumnDefinitions.Add(co1);
//定义第二列
ColumnDefinitionco2=newColumnDefinition();
co2.Width=gl;
grid.ColumnDefinitions.Add(co2);
//添加一个TextBlock显示文件名到第一列
TextBlocktblock=newTextBlock();
tblock.Text=filename;
Grid.SetColumn(tblock,0);
//添加一个HyperlinkButton连接到购物详细清单页面,这是第二列
HyperlinkButtonhybtn=newHyperlinkButton();
hybtn.Content="详细信息";
GridLengthglth=newGridLength(200);
hybtn.Width=200;
hybtn.NavigateUri=newUri("/IsoFilePage.xaml?name="+filename,UriKind.Relative);//传递文件名称到商品详细页面
Grid.SetColumn(hybtn,1);
grid.Children.Add(tblock);
grid.Children.Add(hybtn);
Files.Items.Add(grid);
}
}
}
}
}


ViewCode
添加商品界面:





<Gridx:Name="LayoutRoot"Background="Transparent">
<Grid.RowDefinitions>
<RowDefinitionHeight="Auto"/>
<RowDefinitionHeight="*"/>
</Grid.RowDefinitions>

<!--TitlePanel包含应用程序的名称和页标题-->
<StackPanelGrid.Row="0"Margin="12,17,0,28">
<TextBlockText="我的应用程序"Style="{StaticResourcePhoneTextNormalStyle}"/>
<TextBlockText="添加商品"Margin="9,-7,0,0"Style="{StaticResourcePhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel-在此处放置其他内容-->
<Gridx:Name="ContentPanel"Grid.Row="1"Margin="12,0,12,0">
<TextBlockHorizontalAlignment="Left"Height="35"Margin="23,52,0,0"TextWrapping="Wrap"Text="名称"VerticalAlignment="Top"Width="84"/>
<TextBoxName="MC"HorizontalAlignment="Left"Height="64"Margin="107,36,0,0"TextWrapping="Wrap"Text=""VerticalAlignment="Top"Width="251"FontSize="17"/>
<TextBlockHorizontalAlignment="Left"Height="35"Margin="23,121,0,0"TextWrapping="Wrap"Text="价格"VerticalAlignment="Top"Width="84"/>
<TextBoxName="JG"HorizontalAlignment="Left"Height="64"Margin="107,105,0,0"TextWrapping="Wrap"Text=""VerticalAlignment="Top"Width="251"FontSize="17"/>
<TextBlockHorizontalAlignment="Left"Height="35"Margin="23,185,0,0"TextWrapping="Wrap"Text="数量"VerticalAlignment="Top"Width="84"/>
<TextBoxName="SL"HorizontalAlignment="Left"Height="64"Margin="107,169,0,0"TextWrapping="Wrap"Text=""VerticalAlignment="Top"Width="251"FontSize="17"/>
<ButtonContent="保存"Name="btn_add"HorizontalAlignment="Left"Height="76"Margin="257,411,0,0"VerticalAlignment="Top"Width="151"/>

</Grid>
</Grid>


ViewCode





usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Navigation;
usingMicrosoft.Phone.Controls;
usingMicrosoft.Phone.Shell;
usingSystem.IO.IsolatedStorage;
usingSystem.Xml.Linq;

namespacePhoneApp1
{
publicpartialclassIsoFileAdd:PhoneApplicationPage
{
publicIsoFileAdd()
{
InitializeComponent();
btn_add.Click+=btn_add_Click;
}

voidbtn_add_Click(objectsender,RoutedEventArgse)
{
using(IsolatedStorageFilestorage=IsolatedStorageFile.GetUserStoreForApplication())
{
XDocument_doc=newXDocument();
XElement_item=newXElement(MC.Text);//创建一个XML元素
XAttributeprice=newXAttribute("price",JG.Text);//创建一个XML属性
XAttributecount=newXAttribute("count",SL.Text);
_item.Add(price,count);//将这两个属性添加到XML元素上
//用_item新建一个XML的Linq文档
_doc=newXDocument(newXDeclaration("1.0","utf-8","yes"),_item);
//创建一个独立存储的文件流
IsolatedStorageFileStreamlocation=newIsolatedStorageFileStream(MC.Text+".item",System.IO.FileMode.Create,storage);
//将独立存储文件流转化为可写流
System.IO.StreamWriterfile=newSystem.IO.StreamWriter(location);
//将XML文件保存到file上,即已经写入到手机独立存储文件上
_doc.Save(file);
file.Dispose();//关闭可写流
location.Dispose();//关闭手机独立存储流
//调回清单主页
NavigationService.Navigate(newUri("/IsoFiles.xaml",UriKind.Relative));

}

}
}
}


ViewCode
商品详细界面:





<Gridx:Name="LayoutRoot"Background="Transparent">
<Grid.RowDefinitions>
<RowDefinitionHeight="Auto"/>
<RowDefinitionHeight="*"/>
</Grid.RowDefinitions>

<!--TitlePanel包含应用程序的名称和页标题-->
<StackPanelGrid.Row="0"Margin="12,17,0,28">
<TextBlockText="我的应用程序"Style="{StaticResourcePhoneTextNormalStyle}"/>
<TextBlockText="详细信息"Margin="9,-7,0,0"Style="{StaticResourcePhoneTextTitle1Style}"/>
</StackPanel>

<!--ContentPanel-在此处放置其他内容-->
<Gridx:Name="ContentPanel"Grid.Row="1"Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinitionHeight="63*"/>
<RowDefinitionHeight="77*"/>
<RowDefinitionHeight="467*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinitionWidth="5*"/>
<ColumnDefinitionWidth="19*"/>
</Grid.ColumnDefinitions>
<TextBlockHorizontalAlignment="Left"Height="42"Margin="22,11,0,0"TextWrapping="Wrap"Text="名称"VerticalAlignment="Top"Width="94"Grid.ColumnSpan="2"/>
<TextBlockName="MC"Grid.Column="1"HorizontalAlignment="Left"Height="42"Margin="10,11,0,0"TextWrapping="Wrap"VerticalAlignment="Top"Width="242"/>
<TextBlockHorizontalAlignment="Left"Height="42"Margin="22,10,0,0"TextWrapping="Wrap"Text="价格"VerticalAlignment="Top"Width="94"Grid.Row="1"Grid.ColumnSpan="2"/>
<TextBlockx:Name="JG"Grid.Column="1"HorizontalAlignment="Left"Height="42"Margin="10,10,0,0"TextWrapping="Wrap"VerticalAlignment="Top"Width="242"Grid.Row="1"/>
<TextBlockHorizontalAlignment="Left"Height="42"Margin="22,10,0,0"TextWrapping="Wrap"Text="数量"VerticalAlignment="Top"Width="94"Grid.Row="2"Grid.ColumnSpan="2"/>
<TextBlockx:Name="SL"Grid.Column="1"HorizontalAlignment="Left"Height="42"Margin="10,10,0,0"TextWrapping="Wrap"VerticalAlignment="Top"Width="242"Grid.Row="2"/>
<ButtonContent="返回购物清单"Name="btn_back"Grid.Column="1"HorizontalAlignment="Left"Height="78"Margin="149,379,0,0"Grid.Row="2"VerticalAlignment="Top"Width="182"/>

</Grid>
</Grid>


ViewCode





usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Navigation;
usingMicrosoft.Phone.Controls;
usingMicrosoft.Phone.Shell;
usingSystem.IO.IsolatedStorage;
usingSystem.Xml.Linq;

namespacePhoneApp1
{
publicpartialclassIsoFilePage:PhoneApplicationPage
{
publicIsoFilePage()
{
InitializeComponent();
btn_back.Click+=btn_back_Click;
}

voidbtn_back_Click(objectsender,RoutedEventArgse)
{
NavigationService.Navigate(newUri("/IsoFiles.xaml",UriKind.Relative));
}
//OnNavigatedTo事件是当跳转到当前的页面的时候触发的
protectedoverridevoidOnNavigatedTo(NavigationEventArgse)
{
stringitemName="";
//获取上一页面传过来的item值
boolitemExists=NavigationContext.QueryString.TryGetValue("name",outitemName);
if(itemExists)
{
MC.Text=itemName;
}
using(IsolatedStorageFilestorage=IsolatedStorageFile.GetUserStoreForApplication())
{
XElement_xml;//定义Linq的XML元素
//打开独立存储文件
IsolatedStorageFileStreamlocation=newIsolatedStorageFileStream(itemName,System.IO.FileMode.Open,storage);
//转化为可读流
System.IO.StreamReaderfile=newSystem.IO.StreamReader(location);
//解析流转化为XML
_xml=XElement.Parse(file.ReadToEnd());
if(_xml.Name.LocalName!=null)
{
XAttributeprice=_xml.Attribute("price");//获取价格
JG.Text=price.Value.ToLower();
XAttributecount=_xml.Attribute("count");//获取数量
SL.Text=count.Value.ToLower();
MC.Text=itemName;
}
file.Dispose();
location.Dispose();
}
base.OnNavigatedTo(e);
}
}
}


ViewCode









WP8_读写XML

///<summary>

///WP手机,XML读写类

///</summary>

publicclassWPXmlRW

{

///<summary>

///向WP手机,写入xml文件

///</summary>

///<paramname="argStreamReader"></param>

///<paramname="argFileName">写入的文件名</param>

publicvoidWriteToXml(StreamReaderargStreamReader,stringargFileName="abc.xml")

{

//StreamReadersr=newStreamReader(stream123);//转化为可读流


using(IsolatedStorageFilestorage=IsolatedStorageFile.GetUserStoreForApplication())

{

//解析流转化为XML

XElement_xml=XElement.Parse(argStreamReader.ReadToEnd());


XDocumentdoc=newXDocument(newXDeclaration("1.0","utf-8","yes"),_xml);


//创建一个本地存储的文件流

IsolatedStorageFileStreamlocation=newIsolatedStorageFileStream(argFileName,

System.IO.FileMode.Create,storage);


//将本地存储文件流转化为可写流

System.IO.StreamWriterfile=newSystem.IO.StreamWriter(location);


//将XML文件保存到流file上即已经写入到手机本地存储文件上

doc.Save(file);


file.Dispose();

location.Dispose();

}


}


///<summary>

///从WP手机中,读xml文件

///</summary>

///<paramname="argFileName"></param>

///<returns></returns>

publicXElementReadFromXml(stringargFileName="abc.xml")

{

using(IsolatedStorageFilestorage=IsolatedStorageFile.GetUserStoreForApplication())

{

XElement_xml;//定义Linq的XML元素

//打开本地存储文件

IsolatedStorageFileStreamlocation=newIsolatedStorageFileStream(argFileName,FileMode.Open,storage);

//转化为可读流

System.IO.StreamReaderfile=newSystem.IO.StreamReader(location);

//解析流转化为XML

_xml=XElement.Parse(file.ReadToEnd());


file.Dispose();

location.Dispose();


if(_xml.Name.LocalName!=null)

{

return_xml;

}

}

returnnull;

}

}

乱舞WindowsPhone——xml文件读取

时间:2012-09-0618:19来源:博客园作者:坠翼神祇点击:

525次
WindowsPhone中HttpWebRequest没有提供同步通信方法,我们只能用异步调用,可以使用信号量来模拟同步通信:这里通过AutoResetEvent对象实现,初始设置为Reset,在Response回调方法中置为Set,通过WaitOnt()控制超时时间具体详见代码?xmlversion=1.0?RootLoginRequestUidyonghu1/UidPassword123456/Passwor    WindowsPhone中HttpWebRequest没有提供同步通信方法,我们只能用异步调用,可以使用信号量来模拟同步通信:
  这里通过AutoResetEvent对象实现,初始设置为Reset,在Response回调方法中置为Set,通过WaitOnt()控制超时时间
  具体详见代码
[code]<?xmlversion="1.0"?>
<Root>
<LoginRequest>
<Uid>yonghu1</Uid>
<Password>123456</Password>
</LoginRequest>
<LoginRequest>
<Uid>yonghu2</Uid>
<Password>123456</Password>
</LoginRequest>
<LoginRequest>
<Uid>yonghu3</Uid>
<Password>123456</Password>
</LoginRequest>
</Root>
publicclassLoginRequest
{
publicStringUid{get;set;}
publicStringPassword{get;set;}
}
  其次引用System.Xml.Linq;
1varstream=Application.GetResourceStream(newUri("/BlogTest;component/xml/Login.xml",UriKind.Relative));
2XElementelement=XElement.Load(stream.Stream);
3varloginList=(fromelinelement.Descendants("LoginRequest")
4selectnewLoginRequest
5{
6Uid=el.Element("Uid").Value,
7Password=el.Element("Password").Value
8}).ToArray();
  2:通过XmlReader方式读取xml
  这种方法通过比对节点Name以及节点NodeType来寻找自己需要解析的内容
varreader=XmlReader.Create(stream.Stream);
varloginList=newList<LoginRequest>();
while(reader.Read())
{
if(reader.NodeType==XmlNodeType.Element)
{
if(reader.Name=="LoginRequest")
{
varloginRequest=newLoginRequest();
while(reader.Read()&&reader.NodeType!=XmlNodeType.EndElement)
{
if(reader.Name=="Uid")
{
if(reader.Read())
{
loginRequest.Uid=reader.Value;
}
}
}
while(reader.Read()&&reader.NodeType!=XmlNodeType.EndElement)
{
if(reader.Name=="Password")
{
if(reader.Read())
{
loginRequest.Password=reader.Value;
}
}
}
loginList.Add(loginRequest);
}
}
}
  3:反序列化方式获取xml
  这种方式常用于读取保存后的序列化xml文件,见以下链接:
  http://www.cnblogs.com/zdave/archive/2011/06/01/2067282.html
  本文来自坠翼神祇的博客,原文地址:http://www.cnblogs.com/xiaolongchen/archive/2012/09/05/2672316.html

[/code]



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: