Mohamed Ahmed
Mohamed Ahmed

Reputation: 27

How to deserialize Xml file with nested elements of same name?

I have XML file with this elements:

<Reqs>
    <Source>
        <Sec name="A">
            <Sec name="L">
                <Sec name="B">
                    <Req>
                        <Content></Content>
                        <Title></Title>
                        <Pro></Pro>
                    </Req>
               </Sec>
           </Sec>
      </Sec>
  </Source>
</Reqs>

The elements have the same Name and nested, How I can deserialize it using C# ?

Upvotes: 0

Views: 507

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062502

public class Reqs {
    public Source Source {get;set;}    
}
public class Source {
    public Sec Sec {get;set;}
}
public class Sec {
    [XmlAttribute("name")]
    public string Name {get;set;}
    [XmlElement("Sec")]
    public Sec InnerSec { get; set; }

    public Req Req {get;set;}
}
public class Req {
    public string Content {get;set;}
    public string Title {get;set;}
    public string Pro {get;set;}
}

with:

var reqs = new Reqs {
    Source = new Source {
        Sec = new Sec {
            Name = "A",
            InnerSec = new Sec {
                Name = "L",
                InnerSec = new Sec {
                    Name = "B",
                    Req = new Req {
                        Content = "",
                        Title = "",
                        Pro = ""
                    }
                }
            }
        }
    }
};
var ser = new XmlSerializer(typeof(Reqs));
ser.Serialize(Console.Out, reqs);

Upvotes: 1

Related Questions