I have this XML which has to be Parsed
<category id="1">
<title>Environment & Heritage</title>
<subcategories>
<subcategory id="2">Trees & Green Cover</subcategory>
<subcategory id="3">Noise Pollution</subcategory>
<subcategory id="4">Air Pollution</subcategory>
<subcategory id="5">Water Pollution</subcategory>
</category>
<category id="72">
<title>Environment and Heritage</title>
<subcategories/>
</category>
<category id="7">
<title>Health & Sanitation</title>
<subcategories><subcategory id="8">Drains & Sewerage</subcategory>
<subcategory id="9">Solid Waste Management</subcategory>
</subcategories>
</category>
The class is
public class Categories
{
public string Id { get; set; }
public string Title { get; set; }
public List<Categories> subCategories { get; set; }
public Categories() { }
public Categories(string value, string text)
{
this.Id = value;
this.Title = text;
}
}
we have list of object of this class List
this function is doing the main work
List<Categories> FillObjectFromXML(string xmString)
{
//Declaration
XDocument xmlDoc = XDocument.Load(new StringReader(xmString));
List<Categories> categoriesList = new List<Categories>();
Categories catItem;// = new Categories();
Categories subItem;
List<Categories> subCategoriesList;// = new List<Categories>();
//Coding
var lv1s = from lv1 in xmlDoc.Descendants("category")
select new
{
Id = lv1.Attribute("id").Value,
Header = lv1.Descendants("title"),
Children = lv1.Descendants("subcategories")
};
//Loop through results
foreach (var lv1 in lv1s)
{
catItem = new Categories();
catItem.Id = lv1.Id;
catItem.Title = lv1.Header.First().Value;
subCategoriesList = new List<Categories>();
foreach (var lv2 in lv1.Children)
{
subItem=new Categories();
subItem.Id=lv2.Attribute("id").Value;
subItem.Title=lv2.Descendants("title").ToString();
subCategoriesList.Add(subItem);
}
catItem.subCategories = subCategoriesList;
categoriesList.Add(catItem);
}
//End
return categoriesList;
}
foreach loop for lv2 is not getting the right results
In you method above I believe you need to change the line:
to:
If you like XPath you could probably simplify this code.
Level one categories:
You can then foreach round each of the categories:
Thus removing much of the DOM walking you have to do. Depends on if you like XPath or not – but it’s great for this.