I have the following xml file.
<a>
<b>
<c>val1</c>
<d>val2</d>
</b>
<b>
<c>val3</c>
<d>val4</d>
</b>
<a>
I want to deserialize this into a class and I want to access them with the objects of the class created. I am using C#. I am able to deserialize and get the value into the object of class ‘a’ (the <a> tag). but how to access the value of <b> from this object?
I did the following coding:
[Serializable()]
[XmlRoot("a")]
public class a
{
[XmlArray("a")]
[XmlArrayItem("b", typeof(b))]
public b[] bb{ get; set; }
}
[Serializable()]
public class b
{
[XmlElement("c")]
public string c{ get; set; }
[XmlElement("d")]
public string d{ get; set; }
}
class Program
{
static void Main(string[] args)
{
a i = null;
string path = "test.xml";
XmlSerializer serializer = new XmlSerializer(typeof(a));
StreamReader reader = new StreamReader(path);
i = (a)serializer.Deserialize(reader);
reader.Close();
//i want to print all b tags here
Console.Read();
}
}
For this to work you can make the following change
public class a
{
[XmlElement("b")]
public b[] bb{ get; set; }
}
By using the XmlElement attribute on the array, you are essentially telling the serializer that the array elements should be serialize/deserialized as direct child elements of the current element.
Here is a working example, I put the XML in a string just to make the example self contained.
using System;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
@"<a>
<b>
<c>val1</c>
<d>val2</d>
</b>
<b>
<c>val3</c>
<d>val4</d>
</b>
</a>";
XmlSerializer xs = new XmlSerializer(typeof(a));
a i = (a)xs.Deserialize(new StringReader(xml));
if (i != null && i.bb != null && i.bb.Length > 0)
{
Console.WriteLine(i.bb[0].c);
}
else
{
Console.WriteLine("Something went wrong!");
}
Console.ReadKey();
}
}
[XmlRoot("a")]
public class a
{
[XmlElement("b")]
public b[] bb { get; set; }
}
public class b
{
[XmlElement("c")]
public string c { get; set; }
[XmlElement("d")]
public string d { get; set; }
}
}
When in doubt with creating your xml serialization classes, i find the easiest way to solve the problem is to:
i wrote a quick tutorial on it in a blog post a while ago: http://www.diaryofaninja.com/blog/2010/05/07/make-your-xml-stronglytyped-because-you-can-and-its-easy
it takes less than a minute and you can then easily tweak things from there. XSD.exe is your friend
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With