1

This is my input XML file:

<?xml version="1.0" encoding="UTF-8"?>
<hosts>
  <host>
    <hostId>239|BS|OWN</hostId>
    <images>
      <image>
        <name>Pic.jpg</name>
        <main>true</main>
        <source>../Images/Melissa/Pic.jpg</source>
      </image>
    </images>
  </host>
</hosts>

and this is my class used to deserialiaze that XML file:

[XmlRoot("hosts")]
public class hosts
{
    [XmlElement("host")]       
    public List<Host> Listehosts { get; set; }
}


public class Host
{
    [XmlElement("hostId")]
    public string hostId { get; set; }              

    [XmlElement("images")]
    public List<Image> Listeimages { get; set; }
}


public class Image
{
    [XmlElement("name")]
    public string name { get; set; }
    [XmlElement("main")]
    public string main { get; set; }
    [XmlElement("source")]
    public string source { get; set; }      
}

And this the code of my main program:

string outputTmp = "Images.xml";
XmlSerializer deserializer = new XmlSerializer(typeof(hosts));
TextReader reader = new StreamReader(outputTmp);
object obj = deserializer.Deserialize(reader);
hosts XmlData = (hosts)obj;
reader.Close();            
Console.WriteLine(XmlData.Listehosts.Count);

The problem is that always images list are empty when I execute my program. The list of hosts is charged correctly but when I checked the list of image it contains permanently null value for all the attribute (name, main, source).

Am I missing something?

2 Answers 2

1

Try this :

    public class Host
    {
         [XmlElement("hostId")]
         public string hostId { get; set; }              

         [XmlArray("images")] // CHANGED
         [XmlArrayItem("image", typeof(Image))] // CHANGED
         public List<Image> Listeimages { get; set; }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

There is a small mistake in your code, add an ImageCollection class with a list inside.

public class ImageCollection
{
    [XmlElement("image")]  
    public List<Image> Listeimages { get; set; }
}

public class Host
{
     [XmlElement("hostId")]
     public string hostId { get; set; }              

     [XmlElement("images")]
     public ImageCollection ImageCollection { get; set; }
}

1 Comment

HI Sepehr Farshid , that's method is also working thank you a lot for identifing my mistake.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.