如何使用同名的嵌套元素反序列化Xml文件?

时间:2014-10-07 12:24:49

标签: c# xml

我有这个元素的XML文件:

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

元素具有相同的名称和嵌套,如何使用C#反序列化它?

1 个答案:

答案 0 :(得分:1)

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

使用:

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);