1

Building an XML tree from an Array of "strings/that/are/paths" (in Ruby)

Refering to the question given in the above link, i am looking for a similar implementation in C#.

Can anyone help me get the code to do that.

Community
  • 1
  • 1
user599198
  • 11
  • 1

1 Answers1

0

Here's how I would do it. I'd certainly appreciate any feedback from others.

var paths = new[]
                        {
                            "nodeA1",
                            "nodeA1/nodeB1/nodeC1",
                            "nodeA1/nodeB1/nodeC1/nodeD1/nodeE1",
                            "nodeA1/nodeB1/nodeC2",
                            "nodeA1/nodeB2/nodeC2"
                        };

var xml = new XElement("xml");

foreach (var path in paths)
{
    var parts = path.Split('/');
    var current = xml;
    foreach (var part in parts)
    {
        if (current.Element(part) == null)
        {
            current.Add(new XElement(part));
        }
        current = current.Element(part);
    }
}

var result = xml.ToString();

This prints the following:

<xml>
  <nodeA1>
    <nodeB1>
      <nodeC1>
        <nodeD1>
          <nodeE1 />
        </nodeD1>
      </nodeC1>
      <nodeC2 />
    </nodeB1>
    <nodeB2>
      <nodeC2 />
    </nodeB2>
  </nodeA1>
</xml>
holmes
  • 376
  • 2
  • 7
  • Thanks. This is giving me an error while running the code in visual studio. Also what changes should be made to include the duplicates paths also. like if i have two paths like "nodeA1/nodeB1/nodeC2", "nodeA1/nodeB1/nodeC2". I would appreciate if you can help me with this. – user599198 Feb 06 '11 at 20:04