.NET: Deserializing XML

Quick example of deserializing a chunk of XML into a set of classes: –

<?xml version="1.0" encoding="UTF-8"?>

<!-- Parser configuration control XML -->
<parserConfig version="1.0">

<parsers>

<!-- Test-->
<parse count="6" output="[0][3] = [5];">
<checks>
<check index="0" type="whiteSpace" />
<check index="1" type="alphaNumeric" content="test"/>
<check index="2" type="whiteSpace" />
<check index="3" type="alphaNumeric" />
<check index="4" type="separator" />
<check index="5" type="alphaNumeric" />
</checks>
</parse>

<!-- Test2-->
<parse count="4" output="[0][3]();">
<checks>
<check index="0" type="whiteSpace" />
<check index="1" type="alphaNumeric" content="test2"/>
<check index="2" type="whiteSpace" />
</checks>
</parse>

</parsers>

</parserConfig>
[Serializable()]
public class Parse
{
  [XmlAttribute("count")]
  public int Count { get; set; }

  [XmlAttribute("output")]
  public string Output { get; set; }

  [XmlArray("checks")]
  [XmlArrayItem("check", typeof(Check))]
  public Check[] Check { get; set; }
}

[Serializable()]
public class Check
{
  [XmlAttribute("index")]
  public int Index { get; set; }

  [XmlAttribute("type")]
  public string Type { get; set; }

  [XmlAttribute("content")]
  public string Content { get; set; }
}

[Serializable()]
[XmlRoot("parserConfig")]
public class ParserCollection
{
  [XmlArray("parsers")]
  [XmlArrayItem("parse", typeof(Parse))]
  public Parse[] Parse { get; set; }
}

public Parser()
{
  ParserCollection config = null;
  string path = "../../../config.xml";

  XmlSerializer serializer = new XmlSerializer(typeof(ParserCollection));

  StreamReader reader = new StreamReader(path);
  config = (ParserCollection)serializer.Deserialize(reader);
  reader.Close();
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s