2011-01-10 1 views
2

Попытка рекурсивно добавить XElements, перешагнув список категорий.C# Рекурсивный метод, возвращающий нулевую ссылку, ссылка на объект не устанавливается в экземпляр объекта. Объекты XElement

XElement dataResponse = new XElement("Categories", 
             from c in db.Categories 
             where c.CatTypeID.Equals(catTypeID) && c.ParentID.Equals(null) 
             select new XElement("Category", 
              c.CatID == null ? null : new XAttribute("CatID", c.CatID), 
              c.ParentID == null ? null : new XAttribute("ParentID", c.ParentID), 
              c.CatTitle == null ? null : new XAttribute("CatTitle", c.CatTitle), 
              c.CatTypeID == null ? null : new XAttribute("CatTypeID", c.CatTypeID), 
              c.shortDesc == null ? null : new XAttribute("shortDesc", c.shortDesc), 
              c.longDesc == null ? null : new XAttribute("longDesc", c.longDesc), 
              c.CatImage == null ? null : new XAttribute("CatImage", c.CatImage))); 

        internalData = FillSubCatagories(dataResponse).ToString(); 

Вот первый список категорий Теперь я хочу, чтобы рекурсивно вывести все подкатегорий и гнездо им в моих Xelements FillSubCatagories() метод:

private XElement FillSubCatagories(XElement cat) { 
     IEnumerable<XElement> list = cat.Descendants(); 
     int catTypeID = c.Attribute("CatTypeID") == null ? 1 : Int32.Parse(cat.Attribute("CatTypeID").Value); 
     foreach (XElement c in list) { 
      int parentID = Int32.Parse(cat.Attribute("CatID").Value); 
      XElement sub = new XElement("sub", 
       from s in db.Categories 
       where s.CatTypeID.Equals(catTypeID) && s.ParentID.Equals(parentID) 
       select new XElement("Category", 
        s.CatID == null ? null : new XAttribute("CatID", s.CatID), 
        s.ParentID == null ? null : new XAttribute("ParentID", s.ParentID), 
        s.CatTitle == null ? null : new XAttribute("CatTitle", s.CatTitle), 
        s.CatTypeID == null ? null : new XAttribute("CatTypeID", s.CatTypeID), 
        s.shortDesc == null ? null : new XAttribute("shortDesc", s.shortDesc), 
        s.longDesc == null ? null : new XAttribute("longDesc", s.longDesc), 
        s.CatImage == null ? null : new XAttribute("CatImage", s.CatImage))); 
      c.Add(sub); 
      FillSubCatagories(c); 
     } 
     return cat; 
    } 

Хорошо так проблема возникает, когда я бегу через во второй раз через метод. На int parentID = Int32.Parse(cat.Attribute("CatID").Value); возвращает nullreferenceException - «Ссылка на объект не установлена ​​на экземпляр объекта»

По-прежнему привыкает к C#, исходящему из java, поэтому будьте нежны. Я уверен, что это вопиющая ошибка, но я не видел чистой причины.

< < < < < < < < < >>>>>>>>>>>>>> EDITED новые FillSubCategories() выглядит следующим образом

private XElement FillSubCatagories(XElement cat) { 
     IEnumerable<XElement> list = cat.Descendants(); 
     int catTypeID = cat.Attribute("CatTypeID") == null ? 1 : Int32.Parse(cat.Attribute("CatTypeID").Value); 
     foreach (XElement c in list) { 
      int parentID = Int32.Parse(c.Attribute("CatID").Value); 
      XElement sub = new XElement("sub", 
       from s in db.Categories 
       where s.CatTypeID.Equals(catTypeID) && s.ParentID.Equals(parentID) 
       select new XElement("Category", 
        s.CatID == null ? null : new XAttribute("CatID", s.CatID), 
        s.ParentID == null ? null : new XAttribute("ParentID", s.ParentID), 
        s.CatTitle == null ? null : new XAttribute("CatTitle", s.CatTitle), 
        s.CatTypeID == null ? null : new XAttribute("CatTypeID", s.CatTypeID), 
        s.shortDesc == null ? null : new XAttribute("shortDesc", s.shortDesc), 
        s.longDesc == null ? null : new XAttribute("longDesc", s.longDesc), 
        s.CatImage == null ? null : new XAttribute("CatImage", s.CatImage))); 
      c.Add(sub); 
      if (sub.Descendants() != null) { 
       FillSubCatagories(sub); 
      } 
     } 
     return cat; 
    } 

это у меня много дальше но я все равно в конечном итоге ударил нуль.

EDIT РАБОЧИЙ МЕТОД

private void FillSubCategories(XElement cat) { 
     IEnumerable<XElement> list = cat.Descendants(); 
     foreach (XElement c in list) { 
      try { 
       int catTypeID = Int32.Parse(c.Attribute("CatTypeID").Value); 
       int parentID = Int32.Parse(c.Attribute("CatID").Value); 
       XElement sub = new XElement("sub", 
        from s in db.Categories 
        where s.CatTypeID.Equals(catTypeID) && s.ParentID.Equals(parentID) 
        select new XElement("Category", 
         s.CatID == null ? null : new XAttribute("CatID", s.CatID), 
         s.ParentID == null ? null : new XAttribute("ParentID", s.ParentID), 
         s.CatTitle == null ? null : new XAttribute("CatTitle", s.CatTitle), 
         s.CatTypeID == null ? null : new XAttribute("CatTypeID", s.CatTypeID), 
         s.shortDesc == null ? null : new XAttribute("shortDesc", s.shortDesc), 
         s.longDesc == null ? null : new XAttribute("longDesc", s.longDesc), 
         s.CatImage == null ? null : new XAttribute("CatImage", s.CatImage))); 
       try { 
        string i = sub.Element("Category").Value; 
        c.Add(sub); 
        FillSubCategories(sub); 
       } catch (Exception) { 
        continue; 
       } 
      } catch (Exception) { 
       continue; 
      } 
     } 
    } 
+0

Возможно, однако фактические данные я должен иметь, по крайней мере, еще 3 уровня для категорий. То, что я заметил, это то, что в первый раз, когда я просматриваю список, мой XElement является элементом категории с атрибутами под ним, однако во второй раз я добавляю вспомогательный элемент вместе с его элементом категории, то есть на cat i не будет атрибута , Поэтому я предполагаю, что либо просто перешел в элемент категории подполей, либо настроил какой-то первый атрибут pull для запуска из cat, второй и все последующие прогоны вытащить атрибут descendents. Однако я думаю, что это будет запутывать быстро. – Fozz

+0

См. Http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net –

ответ

0

Это не выглядит хорошо. Вы уверены, что в вашей таблице есть вещи, которые не входят ни в какую категорию? Если это так, вы не должны выбирать их, так как выполняете всю операцию над categoryId. Думаю, как сказал Крис, вы получаете это исключение, потому что вы находитесь на родительской категории, у которой нет другого родителя. Вам нужно поставить условие if и не анализировать, если это родительская категория. Что-то вроде этого:

private XElement FillSubCatagories(XElement cat) { 
     IEnumerable<XElement> list = cat.Descendants(); 
     int catTypeID = c.Attribute("CatTypeID") == null ? 1 : Int32.Parse(cat.Attribute("CatTypeID").Value); 
     foreach (XElement c in list) { 
     if(!String.IsNullOrEmpty(cat.Attribute("CatID").Value)) 
     { 
      int parentID = Int32.Parse(cat.Attribute("CatID").Value); 
      XElement sub = new XElement("sub", 
       from s in db.Categories 
       where s.CatTypeID.Equals(catTypeID) && s.ParentID.Equals(parentID) 
       select new XElement("Category", 
        s.CatID == null ? null : new XAttribute("CatID", s.CatID), 
        s.ParentID == null ? null : new XAttribute("ParentID", s.ParentID), 
        s.CatTitle == null ? null : new XAttribute("CatTitle", s.CatTitle), 
        s.CatTypeID == null ? null : new XAttribute("CatTypeID", s.CatTypeID), 
        s.shortDesc == null ? null : new XAttribute("shortDesc", s.shortDesc), 
        s.longDesc == null ? null : new XAttribute("longDesc", s.longDesc), 
        s.CatImage == null ? null : new XAttribute("CatImage", s.CatImage))); 
      c.Add(sub); 
      FillSubCatagories(c); 
      } 
     } 
     return cat; 
    } 
+0

Разве ваш оператор if не прерывает рекурсию, а просто возвращает? По крайней мере, я почти уверен, что то, что происходит в java. (Я должен был бы это проверить. - И я знаю, что C# не является java, где я пришел раньше, чем C#) – Fozz

0

Там нет атрибута "CatID" на узле, указанного "кошки". Может быть, вы попали в верхнюю часть иерархии?

0

Проблема в том, что cat.Attribute("CatID") - null. Вы делаете cat.Attribute("CatID").Value по нулевому значению, вы получаете эту ошибку.

Вы можете поставить чек, указав, что если он не является нулевым, то продолжайте. Или был другой вопрос?

 Смежные вопросы

  • Нет связанных вопросов^_^