我有一个这样的 XML 结构:
<?xml version="1.0" encoding="utf-8"?>
<categories version="2.0">
<category>
<name>cat1</name>
<category>
<name>cat 1.1</name>
</category>
<category>
<name>cat 1.2</name>
</category>
</category>
</categories>
我尝试使用以下代码将此 XML 转换为对象:
XElement root = XDocument.Load(categoryXmlFile).Descendants("categories").First();
CategoryXml cat = new CategoryXml(root);
class CategoryXml
{
public string Name { get; set; }
public int Level { get; set; }
public int Order { get; set; }
public CategoryXml Parent { get; set; }
public List<CategoryXml> Children { get; set; }
CategoryXml() { }
public CategoryXml(XElement root)
{
Name = "Root Category";
Level = 0;
Order = 1;
Parent = null;
Children = GetSubCategories(root, Level, this);
}
private List<CategoryXml> GetSubCategories(XElement parentElement, int level, CategoryXml parentCategory)
{
int order = 1;
level++;
var s = from childElement in parentElement.Elements("category")
select new CategoryXml
{
Name = childElement.Element("name").Value,
Level = level,
Order = order++,
Parent = parentCategory,
Children = GetSubCategories(childElement, level, this)
};
return s.ToList();
}
}
但是,每个子类别的 Parent 属性都显示为“根类别”。相反,“cat 1.1”的 Parent 属性应该是“cat1”。
我在这里想念什么?