开发者

Building an XML tree from an Array of “strings/that/are/paths” in C#

开发者 https://www.devze.com 2023-02-07 19:59 出处:网络
Building an XML tree from an Array of "s开发者_如何学Gotrings/that/are/paths" (in Ruby)

Building an XML tree from an Array of "s开发者_如何学Gotrings/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.


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消