我可以使用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在这个StackOverflow问题上发布了更好的答案。