我有一个像这样的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属性都显示为“Root Category”。相反,“cat 1.1”的Parent属性应该说“cat1。”
我在这里缺少什么?
答案 0 :(得分:2)
在GetSubCategories
中,您正在使每个孩子的父母成为当前对象的父级:
select new CategoryXml
{
...
Parent = parentCategory,
...
}
我认为你的意思是:
select new CategoryXml
{
...
Parent = this,
...
}
毕竟,每个孩子的父母都是创建孩子的对象,对吗?
但是,我建议您实际调用select
子句中的构造函数,如下所示:
private CategoryXml(XElement current, string name, int level, int order,
CategoryXml parent)
{
Name = name;
Level = level;
Order = order;
Parent = parent;
Children = current.Elements("category")
.Select((child, index) => new CategoryXml(child,
(string) child.Element("name"),
Level + 1,
index + 1,
this))
.ToList();
}
public CategoryXml(XElement root)
{
this(root, "Root Category", level: 0, order: 1, parent: null);
}