【问题标题】:Building an XML tree from an Array of “strings/that/are/paths” in C#在 C# 中从“strings/that/are/paths”数组构建 XML 树
【发布时间】:2011-06-19 15:04:04
【问题描述】:

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

参考上面链接中给出的问题,我正在寻找 C# 中的类似实现。

任何人都可以帮我获取执行此操作的代码。

【问题讨论】:

  • 为什么不自己尝试一下,如果遇到具体问题再回来?

标签: c# xml string path tree


【解决方案1】:

我会这样做。我当然会感谢其他人的任何反馈。

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();

这将打印以下内容:

<xml>
  <nodeA1>
    <nodeB1>
      <nodeC1>
        <nodeD1>
          <nodeE1 />
        </nodeD1>
      </nodeC1>
      <nodeC2 />
    </nodeB1>
    <nodeB2>
      <nodeC2 />
    </nodeB2>
  </nodeA1>
</xml>

【讨论】:

  • 谢谢。在 Visual Studio 中运行代码时,这给了我一个错误。此外,还应进行哪些更改以包含重复路径。就像我有两条路径,如“nodeA1/nodeB1/nodeC2”、“nodeA1/nodeB1/nodeC2”。如果您能帮我解决这个问题,我将不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-11
  • 2021-12-31
  • 2013-02-22
  • 1970-01-01
相关资源
最近更新 更多