使用 Linq 生成分层 XML
我有以下类,该类应该表示分层数据结构
class Person
{
int Id { get; set; }
Person Parent { get; set; }
List<Person> Children { get; set; }
}
在我的 UI 中,我收到一个 Person 集合,其中每个人都可能有子对象。 我需要打印出具有以下结构的 XML:
<root>
<Person id="1" parent_id="0" name="">
<Person id="5" parent_id="1" name="">
<Person id="10" parent_id="5" name="">
</Person>
</Person>
<Person id="6" parent_id="1" name="">
</Person>
</Person>
<Person id="2" parent_id="0" name="">
</Person>
</root>
现在我写了这个,但我的代码不是递归的。 你能帮我使用 LINQ 完成这件事吗?
public XDocument GetHtmlWorkbookTree(List<Person> persons)
{
var document = new XDocument();
var root = new XElement("Person",
persons.Select(
r => new XElement("Person",
new XAttribute("id", r.Id))));
document.Add(root);
return document;
}
I have the following class that is supposed to represent a hierarchical data structure
class Person
{
int Id { get; set; }
Person Parent { get; set; }
List<Person> Children { get; set; }
}
In my UI I receive a collection of Person where each one may have children.
I need to print out an XML with the following structure:
<root>
<Person id="1" parent_id="0" name="">
<Person id="5" parent_id="1" name="">
<Person id="10" parent_id="5" name="">
</Person>
</Person>
<Person id="6" parent_id="1" name="">
</Person>
</Person>
<Person id="2" parent_id="0" name="">
</Person>
</root>
Right now I wrote this but my code is not recursive.
Can you help me on getting this done using LINQ?
public XDocument GetHtmlWorkbookTree(List<Person> persons)
{
var document = new XDocument();
var root = new XElement("Person",
persons.Select(
r => new XElement("Person",
new XAttribute("id", r.Id))));
document.Add(root);
return document;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这没什么大不了的,和任何递归一样。只需将 XElement 传递给递归函数即可。
我在想这样的事情:
我不确定这是否会正常工作,因为我现在没有 VS 来测试它,但我希望你明白这个想法!
It's not that big a deal, it's the same as any recursion. Just pass on the XElement to the recursive function.
I'm thinking something like this:
I'm not sure that this will work as it is, since I don't have VS right now to test it, but I hope you get the idea!