2009-06-16 63 views
14

我可以使用的XDocument建立以下文件,该文件工作正常如何使用foreach和LINQ构建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 
} 

There is AddAddFirstAddAfter自我,AddBeforeSelf,但我不能让他们在这方面工作。

像这样可以迭代LINQ吗?

答:

我把吉米的代码暗示本根标签,改变它一点,它正是我一直在寻找:

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

马克Gravell发布更好的回答这on this StackOverflow question

回答

25

你需要一个根元素。

var xdoc = new XDocument(
    new XDeclaration("1.0", "utf-8", null), 
    new XElement("Root", 
     _dataTypes.Select(datatype => new XElement(datatype._pluralCamelNotation, 
      new XElement(datatype._singlarCamelNotation), 
      new XElement("id", "1"), 
      new XElement("whenCreated", "2008-12-31") 
     )) 
    ) 
); 
+0

很光滑,谢谢! – 2009-06-16 16:08:36

2

简单的Add method有什么问题?

+2

我猜测作者想要LINQ解决方案解决此问题,除非似乎没有。其实,这是一个有趣的问题 - 如何将一个IEnumerable变成一个合适的参数列表=) – 2009-06-16 16:03:01

3

如果我没有记错,你应该能够使用XDocument.Add():

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.Add(xelement); 
} 
+2

当我使用该代码时,我得到“这将创建一个错误结构的XML文档”,我试图用“测试”和“测试”,但同样的错误。 – 2009-06-16 16:03:06

3

我知道这是非常非常老的文章,但我今天这个偶然发现试图解决同样的问题。您必须将元素添加到文档的根目录中:

xdoc.Root.Add(xelement);