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.

1
  • 2
    Why don't you try it out yourself and come back if you have a specific problem? Commented Feb 1, 2011 at 23:41

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.