Попытка рекурсивно добавить 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;
}
}
}
Возможно, однако фактические данные я должен иметь, по крайней мере, еще 3 уровня для категорий. То, что я заметил, это то, что в первый раз, когда я просматриваю список, мой XElement является элементом категории с атрибутами под ним, однако во второй раз я добавляю вспомогательный элемент вместе с его элементом категории, то есть на cat i не будет атрибута , Поэтому я предполагаю, что либо просто перешел в элемент категории подполей, либо настроил какой-то первый атрибут pull для запуска из cat, второй и все последующие прогоны вытащить атрибут descendents. Однако я думаю, что это будет запутывать быстро. – Fozz
См. Http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net –