【问题标题】:How to build an XDocument with a foreach and LINQ?如何使用 foreach 和 LINQ 构建 XDocument?
【发布时间】: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
}

AddAddFirstAddAfterSelfAddBeforeSelf,但我无法让它们中的任何一个工作在这种情况下。

这样的 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 发布了更好的答案。

【问题讨论】:

    标签: c# xml linq


    【解决方案1】:

    你需要一个根元素。

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

    【讨论】:

      【解决方案2】:

      如果我没记错的话,你应该可以使用 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);
      }
      

      【讨论】:

      • 当我使用该代码时,我得到“这将创建一个结构错误的 XML 文档”,我尝试用“tests”和“test”替换变量,但同样的错误。
      【解决方案3】:

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

      xdoc.Root.Add(xelement);
      

      【讨论】:

        【解决方案4】:

        简单的Add method有什么问题?

        【讨论】:

        • 我猜作者想要一个 LINQ 解决方案来解决这个问题,但似乎没有。其实这是一个有趣的问题——如何把一个IEnumerable变成一个合适的参数列表=)
        猜你喜欢
        • 2011-03-18
        • 1970-01-01
        • 2011-06-01
        • 2020-07-25
        • 1970-01-01
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多