Convert List to XML

For the project I'm currently working on, I have been given an array of objects, each of which contains the "content" property and the "level" property. I need to convert this list to an HTML bulleted list. For example, if I was provided with the following input (shown in JSON for simplicity):

[ {content: "Hey", level: "1"},
  {content: "I just met you", level: "2"},
  {content: "and this is crazy", level: "2"},
  {content: "but here my number", level: "1"},
  {content: "call me, maybe", level: "3"} ]

I need to convert it to the following XHTML:

<ul>
  <li>Hey</li>
  <li>
    <ul>
      <li>I just met you</li>
      <li>and this is crazy</li>          
    </ul>
  </li>
  <li>but here my number</li>
  <li>
    <ul>
      <li>
        <ul>
          <li>call me, maybe</li>      
        </ul>
      </li>
    </ul>
  </li>
</ul>

The final product will look like this:

  • Hey
    • I just met you.
    • and this is crazy
  • but here is my number
    • call me, maybe ( <- one level deeper ), I don’t think I can do it in SO)

. - /, / ? #, / .

+5
1

, , , , , .

public string BuildLists(List<KeyValuePair<string, int>> pairs)
{
    int CurrentLevel = 1;
    StringBuilder s = new StringBuilder();

    s.Append("<ul>");

    foreach (KeyValuePair<string, int> pair in pairs)
    {
        if(pair.Value > CurrentLevel)
        {
            //Nest more
            for(int i = 0; i < pair.Value - CurrentLevel; i++)
            {
                s.Append("<li><ul>");
            }
        }
        else if(pair.Value < CurrentLevel)
        {
            //Close Tags
            for(int i = 0; i < CurrentLevel - pair.Value; i++)
            {
                s.Append("</ul></li>");
            }
        }

        s.Append("<li>" + pair.Key + "</li>");

        CurrentLevel = pair.Value
    }

    //Close everything.
    for(int i = 0; i < CurrentLevel - 1; i++)
    {
        s.Append("</ul></li>");
    }

    s.Append("</ul>");
    return s.ToString();
}
+2

All Articles