我试图从C#中的xml创建以下树结构:
Root
-->A
--->1
--->2
-->B
--->1
--->2
Run Code Online (Sandbox Code Playgroud)
xml会是这样的:
<root>
<parent1 name="A">
<child name=1>
<child name=2>
</parent1>
<parent2 name="B">
<child name=1>
<child name=2>
</parent2>
</root>
Run Code Online (Sandbox Code Playgroud)
任何准则?
假设你想要它的ASCII艺术......这个单行Linq查询:
string tree = doc.Root.DescendantsAndSelf().Aggregate("",
(bc, n) => bc + n.Ancestors().Aggregate("", (ac, m) => (m.ElementsAfterSelf().Any() ? "| " : " ") + ac,
ac => ac + (n.ElementsAfterSelf().Any() ? "+-" : "\\-")) + n.Name + "\n");
Run Code Online (Sandbox Code Playgroud)
将您的XML转换为:
\-Root
\-parent1
| +-child
| \-child
\-parent2
+-child
\-child
Run Code Online (Sandbox Code Playgroud)
我是否因为单线答案而获奖?;-)