0

我有一个这样的 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”。

我在这里想念什么?

4

1 回答 1

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);
}
于 2012-05-19T00:00:46.777 回答