Reputation: 196539
I have this html as a reference and I have a set of hierarchy data. The names of the nodes are hopefully helpful to understand where they fit in the chain
here is the reference html (hardcoded)
<ul id="tree1">
<li><input type="checkbox"><label>Node 1</label>
<ul>
<li><input type="checkbox"><label>Node 1.1</label>
<ul>
<li><input type="checkbox"><label>Node 1.1.1</label>
</ul>
</ul>
<ul>
<li><input type="checkbox"><label>Node 1.2</label>
<ul>
<li><input type="checkbox"><label>Node 1.2.1</label>
<li><input type="checkbox"><label>Node 1.2.2</label>
<ul>
<li><input type="checkbox"><label>Node 1.2.3.1</label> <li><input type="checkbox"><label>Node 1.2.3.2</label>
</ul>
<li><input type="checkbox"><label>Node 1.2.4</label>
<li><input type="checkbox"><label>Node 1.2.5</label>
<li><input type="checkbox"><label>Node 1.2.6</label>
</ul>
</ul>
<li><input type="checkbox"><label>Node 2</label>
i now need C# code to take this hierarchy of data to generate this html output above. I have a Node object that has a .Children() property. here is what i have so far but i am missing some </ul>
somewhere in this code.
NOTE: that _b is a string builder object that is being used at the end to output a string.
static public void GenerateTree(Node node, bool skipUL)
{
if (node.Children.Count() > 0)
{
bool included = false;
foreach (Node childNode in node.Children)
{
if (!included && !skipUL)
{
_b.AppendLine("<ul>");
included = true;
}
skipUL = false;
_b.AppendLine("<li><input type='checkbox'>" + childNode .Name);
GenerateTree(childNode, skipUL);
}
if (included)
{
_b.AppendLine("</ul>");
}
}
}
Upvotes: 0
Views: 1580
Reputation: 101614
I would take a tad different approach, namely beginning with the collection not the single entity (since chances are your root is going to be a collection, unless this is always going to only have one root element).
That being said:
public static String Dump(List<Node> nodes)
{
if (nodes == null || nodes.Count == 0)
return String.Empty;
StringBuilder sb = new StringBuilder("<ul>");
foreach (var n in nodes)
{
sb.AppendFormat("<li>{0}", n.Name);
sb.Append(Dump(n.Children));
sb.Append("</li>");
}
sb.Append("</ul>");
return sb.ToString();
}
And here's a demo, with a simple mock-up of what I expect your objects to look like:
Upvotes: 1
Reputation: 545618
From what I see you should be fine without the included
and skipUL
tags. The algorithm is straightforward:
<li>
<ul>
</ul>
</li>
There is no need for any special handling. No extra variables are needed.
Upvotes: 0