资源描述
此例为获取Xml文件内的数据
页面内容:
<UserControl x:Class="ToTestData.MainPage"
xmlns="
xmlns:x="
xmlns:d="
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" VerticalAlignment="Stretch" VerticalContentAlignment="Stretch">
<Grid x:Name="LayoutRoot" Background="White">
<Button x:Name="btnTestone" Width="60" Height="40" Background="Pink"></Button>
<TextBlock x:Name ="OutputTextBlock" TextWrapping="Wrap" />
<TextBox x:Name="txtTestone" Canvas.Top="20" Canvas.Left="10" TextWrapping="Wrap" Margin="90,215,277,63" Width="49" Height="22" IsEnabled="False" FontStyle="Italic" Foreground="Blue"></TextBox>
</Grid>
</UserControl>
后台代码
using System;
using System.Windows.Controls;
using System.Xml;
using System.IO;
using System.Text;
using System.Xml.Linq;
namespace ToTestData
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
StringBuilder output = new StringBuilder();
string author = "";
int count = 0;
// XmlXapResolver is the default resolver.
using (XmlReader reader = XmlReader.Create("Data/book.xml"))//括号内为路径
{
// Moves the reader to the root element.
reader.MoveToContent();
for (int i = 0; ; i++)
{
reader.ReadToFollowing("book");
author=reader.ReadOuterXml();
if (author == "")
{
output.AppendLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
break;
}
else
{
if (i != 0)
output.AppendLine("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
int a = i + 1;
output.AppendLine("Read the "+a+" book using ReadOuterXml...");
output.AppendLine(author);
if (i == 0)
{
output.AppendLine("-----------------------------------------");
ShowDetail(output, author);
}
count += 1;
}
}
output.AppendLine("一共 " + count + "个节点");
}
OutputTextBlock.Text = output.ToString();
}
//分段显示
private void ShowDetail(StringBuilder output, string author)
{
using (XmlReader reader = XmlReader.Create(new StringReader(author)))
{
reader.ReadToFollowing("book");
reader.MoveToFirstAttribute();
string genre = reader.Value;
reader.MoveToNextAttribute();
string genre2 = reader.Value;
output.AppendLine("The genre value: " + genre);
output.AppendLine("The ISBN value: " + genre2);
output.AppendLine("Content of the title element: " + GteXml(reader, "title", author));
txtTestone.Text = GteXml(reader, "price", author);
btnTestone.Content = genre;
}
}
//依据标题获取XML中内容
private static string GteXml(XmlReader reader, string name, string author)
{
reader.ReadToFollowing(name);
author = reader.ReadInnerXml();
return author;
}
}
}
以下为效果截屏:
展开阅读全文