Linq to XML, getting items in proper tree structure
I have some XML like this
<case>
<tab tabdescription="text here">
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
</tab>
<tab tabdescription="text here">
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
</tab>
<tab tabdescription="text here">
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
<subtab subtab_description="subtab description here" subttab_text="subtab text here" />
</tab>
<exhibit exhibitdescription="exhibit description here">
<exhibitfilename>FileName.File</exhibitfilename />
</exhibit>
<exhibit exhibitdescription="exhibit description here">
<exhibitfilename>FileName.File</exhibitfilename />
</exhibit>`
<exhibit exhibitdescription="exhibit description here">
<exhibitfilename>FileName.File</exhibitfilename />
</exhibit>
</case>
In my c# code I have a tab object that contains a tabdescription property and a List<subtab>
objects, and the subtab object contains a subtabdescription property and a subtabtext property. I also have an ex开发者_开发知识库hibit object with exhibitdescription and exhibitfilename properties.
I need to populate these objects so that when finished I would have three tab objects each containing their 3 subtab objects with all appropriate fields populated. I would also need 3 exhibit objects populated with their exhibitdescription and exhibitfilename.
I've done a little work with ling to xml before, but I never had to worry about getting the objects out in a perfect tree representation of the xml because usually they have id's where I can go through the lists after the fact and group the items properly. Any help with this would be great.
If you are not familiar with LINQ to XML you could consider to use XmlSerializer to deserialize the XML into your objects, simply by adding some attributes. Or use LINQ to XML e.g.
XDocument doc = XDocument.Load("case.xml");
IEnumerable<Tab> tabs =
from tab in doc.Root.Elements("tab")
select new Tab() {
Description = (string)tab.Attribute("tabdescription"),
Subtabs = (from subtab in tab.Elements("subtab")
select new Subtab() {
Subtabdescription = (string)subtab.Attribute("subtabdescription"),
Subtabtext = (string).subtab.Attribute("subtabtext")
}).ToList()
};
精彩评论