实例使用WPF完成。
简单搭建一个wpf页面如下:
<Window x:Class="WpfDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfDemo"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="53*"/>
<RowDefinition Height="53*"/>
<RowDefinition Height="53*"/>
<RowDefinition Height="293*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="25*"/>
<ColumnDefinition Width="173*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center">ID</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center">Name</TextBlock>
<TextBlock Grid.Row="2" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center">Type</TextBlock>
<TextBox x:Name="TxtID" Width="200" Height="20" Grid.Row="0" Grid.Column="1" HorizontalAlignment="Left"></TextBox>
<TextBox x:Name="TxtName" Width="200" Height="20" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Left"></TextBox>
<TextBox x:Name="TxtType" Width="200" Height="20" Grid.Row="2" Grid.Column="1" HorizontalAlignment="Left"></TextBox>
<Button Grid.Column="1" Grid.Row="3" Width="100" Height="30" Margin="70,50,522,192" x:Name="btnCreateXML" Click="BtnCreateXML_Click">生成</Button>
<Button Grid.Column="1" Grid.Row="3" Width="100" Height="30" Margin="215,50,377,192" x:Name="btnBackfillInfoXML" Click="BtnBackfillInfoXML_Click">回填</Button>
</Grid>
</Window>
效果:
要实现的功能点击生成在程序的bin>debug 文件下根据程序里的一个model生成xml文件。点击回填读取xml文件并将xml里的数据进行回填。
首先在新写一个model类:
public class Model
{
public string ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
用来存储。
给生成点击事件写生成xml的代码:
private void BtnCreateXML_Click(object sender, RoutedEventArgs e)
{
Model model = new Model();//实例化model
model.ID = TxtID.Text;
model.Name = TxtName.Text;
model.Type = TxtType.Text;
Directory.CreateDirectory("Xml");//在bin> debug 文件夹下创建名为Xml的文件夹,除非已经存在。
using (Stream stream = File.Open("Xml/DemoXML.xml", FileMode.Create))//在此路径创建一个新xml文件,如果已存在则覆盖
{
var serializer = new XmlSerializer(model.GetType());//这个是关键。根据model的属性创建xml节点
serializer.Serialize(stream, model);//保存xml文件到路径
}
}
在相应的文本框写上东西点击生成按钮生成在相应路径里能够找到新增的xml文件了
现在给回填按钮写代码:
private void BtnBackfillInfoXML_Click(object sender, RoutedEventArgs e)
{
Model model = new Model();//实例化mdoel用来接收xml的数据
if (File.Exists("Xml/DemoXML.xml"))//确定指定的文件是否存在
{
using (var stream = File.OpenRead("Xml/DemoXML.xml"))
{
var serializer = new XmlSerializer(model.GetType());
model = serializer.Deserialize(stream) as Model;
}
TxtID.Text = model.ID;
TxtName.Text = model.Name;
TxtType.Text = model.Type;
}
}
效果: