我有这个必须解析的XML
<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>
班级
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;
}
}
我们有这个类List的对象列表
这个功能正在做主要的工作
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;
}
lv2的foreach循环没有得到正确的结果
答案 0 :(得分:2)
在上面的方法中,我相信你需要更改一行:
Children = lv1.Descendants("subcategories")
为:
Children = lv1.Descendants("subcategory")
如果你喜欢XPath,你可以简化这段代码。
一级类别:
XmlNodeList categories = xmlDoc.SelectNodes("//category"); //assumes there is only one tier of categories.
然后,您可以围绕每个类别进行预测:
foreach(XmlNode category in categories)
{
XmlNodeList subcategories = category.SelectNodes("./subcategories/subcategory");
}
因此,您需要删除大部分DOM。取决于你是否喜欢XPath - 但这对你来说很棒。
答案 1 :(得分:1)
您的XML目前无效。修复之后,在解析Children
集合时,您正在寻找错误的位置 - 每个子节点都是subcategories
节点 - 您希望它成为subcategory
节点 - 所以更改此:< / p>
Children = lv1.Descendants("subcategories")
到
Children = lv1.Descendants("subcategory")