Using XmlReader and XmlWriter
<UserControl x:Class='SilverlightApplication3.MainPage'
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'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<Grid x:Name="LayoutRoot" Background="LightGray">
<TextBox x:Name = "NameText" Text="Full Name"/>
<TextBox x:Name = "PhoneText" Text="Phone Number"/>
<StackPanel Orientation="Horizontal">
<RadioButton x:Name="HomeBtn" Content="Home" />
<RadioButton x:Name="OfficeBtn" Content="Office" />
<RadioButton x:Name="CellBtn" Content="Cell" />
</StackPanel>
<Button x:Name="XMLWriteBtn" Content="Write XML"/>
<Button x:Name="XMLReadBtn" Content="Read XML"/>
<ScrollViewer Background="White">
<TextBlock x:Name="myText" Margin="5"/>
</ScrollViewer>
</Grid>
</UserControl>
//File:Page.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Xml;
using System.IO;
using System.Text;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
XMLWriteBtn.Click += new RoutedEventHandler(doWrite);
XMLReadBtn.Click += new RoutedEventHandler(doRead);
}
void doWrite(object sender, RoutedEventArgs e)
{
StringBuilder xmlData = new StringBuilder();
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.Indent = true;
XmlWriter writer = XmlWriter.Create(xmlData, wSettings);
writer.WriteStartElement("Contact");
writer.WriteStartElement("FullName");
writer.WriteString(NameText.Text);
writer.WriteEndElement();
writer.WriteStartElement("Phone");
writer.WriteStartAttribute("Type");
if((bool)HomeBtn.IsChecked)
writer.WriteString("Home");
else if ((bool)OfficeBtn.IsChecked)
writer.WriteString("Office");
else if ((bool)CellBtn.IsChecked)
writer.WriteString("Cell");
writer.WriteEndAttribute();
writer.WriteString(PhoneText.Text);
writer.WriteEndElement();
writer.Close();
myText.Text = xmlData.ToString();
}
void doRead(object sender, RoutedEventArgs e)
{
StringBuilder textData = new StringBuilder();
StringReader sReader = new StringReader(myText.Text);
XmlReader reader = XmlReader.Create(sReader);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
textData.Append("Element: " + reader.Name);
if (reader.Name == "Phone"){
string type = reader.GetAttribute("Type");
textData.Append("Attribute: Type = " + type);
}
break;
case XmlNodeType.Text:
textData.Append("Value: " + reader.Value);
break;
case XmlNodeType.XmlDeclaration:
textData.Append("Declaration Name: " + reader.Name);
textData.Append("Declaration Value: " + reader.Value);
break;
case XmlNodeType.EndElement:
break;
}
}
reader.Close();
myText.Text = textData.ToString();
}
}
}
Related examples in the same category