Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Globalization;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Xml;
- using System.Xml.Serialization;
- using NUnit.Framework;
- namespace UnitTests
- {
- [TestFixture]
- public class SoTest
- {
- #region Test
- [Test]
- public void TestDeserializing()
- {
- const string xml = @"<root>
- <company>
- <location>USA</location>
- <name>TopCars</name>
- </company>
- <CarList name=""CarCounts"">
- <ModelList name=""Models"">
- <Column name=""Ford"">50</Column>
- <Column name=""Chevy"">65</Column>
- <Column name=""Dodge"">75</Column>
- </ModelList>
- </CarList>
- </root>";
- var deserializer = new XmlSerializer(typeof(Root));
- Root root;
- using (var stringReader = new StringReader(xml))
- using (var xmlReader = XmlReader.Create(stringReader))
- {
- root = (Root) deserializer.Deserialize(xmlReader);
- }
- var models = new Models(root.CarList.Models);
- Debug.Print(models.Chevy.ToString(CultureInfo.InvariantCulture));
- Debug.Print(models.Ford.ToString(CultureInfo.InvariantCulture));
- }
- #endregion
- #region Shim Class
- class Models
- {
- private readonly List<Model> _models;
- public Models(List<Model> models)
- {
- this._models = models;
- }
- public int Chevy
- {
- get
- {
- var chevy = this._models.Find(model => model.Name == "Chevy");
- if(chevy == null)
- {
- throw new SerializationException("Xml must contain a model called Chevy");
- }
- return chevy.Value;
- }
- }
- public int Ford
- {
- get
- {
- var ford = this._models.Find(model => model.Name == "Ford");
- if (ford == null)
- {
- throw new SerializationException("Xml must contain a model called Ford");
- }
- return ford.Value;
- }
- }
- // etc.
- }
- #endregion
- #region Deserializing Classes
- [XmlRoot("root")]
- public class Root
- {
- [XmlElement("company")]
- public Company Company { get; set; }
- [XmlElement("CarList")]
- public CarList CarList { get; set; }
- }
- public class Company
- {
- [XmlElement("location")]
- public string Location { get; set; }
- [XmlElement("name")]
- public string Name { get; set; }
- }
- public class CarList
- {
- [XmlArray("ModelList")]
- [XmlArrayItem("Column")]
- public List<Model> Models { get; set; }
- }
- public class Model
- {
- [XmlAttribute("name")]
- public string Name { get; set; }
- [XmlText]
- public int Value { get; set; }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement