2012-05-19

Articles

AttributeParser

 

The AttributeParser reads an attribute from a given XElement by the name and returns the value converted like requested.

 

 

Usage

<UserControl x:Class="DW.SharpTools.Demo.AttributeParserControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
			 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
			 mc:Ignorable="d" 
			 d:DesignHeight="300" d:DesignWidth="300">
	<DockPanel Margin="5">
		<Button Content="Parse" DockPanel.Dock="Bottom" HorizontalAlignment="Center" Click="Parse_Click" />
		<TextBox Margin="0,0,0,5" x:Name="xmlDocument" IsReadOnly="True" />
	</DockPanel>
</UserControl>
using System.Globalization;
using System.Windows.Controls;
using System.Xml.Linq;

namespace DW.SharpTools.Demo
{
	public partial class AttributeParserControl : UserControl
	{
		public AttributeParserControl()
		{
			InitializeComponent();

			xmlDocument.Text = GetXml();
		}

		private static string GetXml()
		{
			return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
					"<Example element=\"4.4\" item=\"13\">\n" +
					"</Example>";
		}

		private void Parse_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			var document = XDocument.Parse(xmlDocument.Text);
			var rootElement = document.Element("Example");

			XmlTools.ParserSettings.ParserCulture = new CultureInfo("en-US");
			var itemValue = XmlTools.AttributeParser.ToInt32(rootElement, "item", 1);
			var elementValues = XmlTools.AttributeParser.ToDouble(rootElement, "element", 1.0);
		}
	}
}