The scenario:
Imagine someone asks you to create an XML file with some data structure.
The approuch:
There are several ways to achieve this, the fastest and less time comsuming is to create a class structure that represents the XML structure you need, fill in with the data and them serialize it to a string and save it to a file.
The Implementation:
Lets say you need a single node, followed by an array of nodes.
Class Definition:
public class MyNode
{
[XmlElementAttribute("code")]
public int code;
[XmlElementAttribute("description")]
public string description;
}
public class Item
{
[XmlAttribute("name")]
public string name;
[XmlAttribute("value")]
public string value;
}
[XmlRootAttribute("myClass", IsNullable = false, Namespace = "")]
public class MyClass
{
public MyClass()
{
myNode = new MyNode();
}
[XmlElementAttribute("myNode")]
public MyNode myNode;
[XmlArrayAttribute("myArray")]
public List<Item> myArray = new List<Item>();
public override string ToString()
{
try
{
string xmlString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(MyClass));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, this);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlString = UTF8ByteArrayToString(memoryStream.ToArray());
return xmlString;
}
catch
{
return string.Empty;
}
}
private static string UTF8ByteArrayToString(byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
string constructedString = encoding.GetString(characters);
return (constructedString);
}
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
public static MyClass DeserializeObject(string xml)
{
XmlSerializer xs = new XmlSerializer(typeof(MyClass));
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
return (MyClass)xs.Deserialize(memoryStream);
}
}
Now, to use these classes:
public static string myFunction()
{
MyClass fido = new MyClass();
fido.myNode.code = 1;
fido.myNode.description="sample text";
myArray.Add(new Item{name="name1", value="value1"});
myArray.Add(new Item{name="name2", value="value2"});
return fido.ToString();
}
Executing this you will get an string as such:
<?xml version="1.0" encoding="utf-8"?>
<myClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<myNode>
<code>1</code>
<description>sample text</description>
</myNode>
<myArray>
<Item name="name1" value="value1" />
<Item name="name2" value="value2" />
</myArray>
</myClass>
Using the string returned from "fido.ToString()" in the method DeserializeObject will get you the original values for the object.
Hope this can be helpfull,
Enjoy :)