【发布时间】:2010-11-03 09:26:23
【问题描述】:
我可以使用 XDocument 构建以下工作正常的文件:
XDocument xdoc = new XDocument
(
new XDeclaration("1.0", "utf-8", null),
new XElement(_pluralCamelNotation,
new XElement(_singularCamelNotation,
new XElement("id", "1"),
new XElement("whenCreated", "2008-12-31")
),
new XElement(_singularCamelNotation,
new XElement("id", "2"),
new XElement("whenCreated", "2008-12-31")
)
)
);
但是,我需要像这样遍历集合来构建 XML 文件:
XDocument xdoc = new XDocument
(
new XDeclaration("1.0", "utf-8", null));
foreach (DataType dataType in _dataTypes)
{
XElement xelement = new XElement(_pluralCamelNotation,
new XElement(_singularCamelNotation,
new XElement("id", "1"),
new XElement("whenCreated", "2008-12-31")
));
xdoc.AddInterally(xelement); //PSEUDO-CODE
}
有 Add、AddFirst、AddAfterSelf、AddBeforeSelf,但我无法让它们中的任何一个工作在这种情况下。
这样的 LINQ 迭代是否可行?
答案:
我采用了 Jimmy 的带有根标签的代码建议,对其进行了一些修改,这正是我想要的:
var xdoc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(_pluralCamelNotation,
_dataTypes.Select(datatype => new XElement(_singularCamelNotation,
new XElement("id", "1"),
new XElement("whenCreated", "2008-12-31")
))
)
);
Marc Gravell 对此on this StackOverflow question 发布了更好的答案。
【问题讨论】: