2014-10-07 50 views
0

我有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#反序列化?

+0

你已經嘗試了什麼至今 – 2014-10-07 12:25:57

回答

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

非常感謝你,它的工作完美 – 2014-10-15 14:59:43