6
votes

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();
        }
    }
5
Can you post the code that gets the tag? May give us clues to help. - Oded
If you really deserialized the xml to an object, that'd be a.b. What do you have? Just an XML document, perhaps? - Kobi

5 Answers

8
votes

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; }
  }  
}
2
votes

When in doubt with creating your xml serialization classes, i find the easiest way to solve the problem is to:

  • dump all your dummy data into an XML file
  • run xsd.exe to create a .xsd schema file
  • run xsd.exe on your schema file to create a class file

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

0
votes

I find the easiest way to solve the problem is to change your definition of classes a and b to the following

public class b {
    public string c { get; set; }
    public string d { get; set; }
}

[XmlRoot(Namespace="", ElementName="a")]
public class a : List<b> { }

then your program will work. Optionally you can add to the class b the attribute [XmlRoot (Namespace = "", ElementName = "b")]

0
votes
class Program
{
    static void Main(string[] args)
    {
        string employeedata = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><tag><name>test</bar></nmae>";//demo xml data
        using (TextReader sr = new StringReader(employeedata))
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Employee));//pass type name in XmlSerializer constructor here
            Employee response = (Employee)serializer.Deserialize(sr);
            Console.WriteLine(response.name);
        }

    }
}
[System.Xml.Serialization.XmlRoot("tag")]
public class Employee
{
    public string name { get; set; }
}
-1
votes

Change if block (from Chris Tyler's answer) like below.

 if (i != null && i.bb != null && i.bb.Length > 0)
            {
                foreach (b t in i.bb)
                {
                    Console.WriteLine(t.c);
                    Console.WriteLine(t.d);
                }
            }

then it will give you below result:

val1 val2 val3 val4