如何使用for循环编写XML文件?

时间:2014-06-09 18:59:07

标签: c# xml for-loop

我正在尝试创建一个非常简单的XML文件的快速程序。我想创建一个使用' for循环的XML文件。多次创建XML的一部分。当我建立时,我得到一个错误说" '表达式用语无效。我检查了我的括号平衡,它似乎确实检查出来。

有谁知道这个错误意味着什么?

    static void Main(string[] args)
    { 
        XDocument myDoc = new XDocument(
        new XDeclaration("1.0" ,"utf-8","yes"),
        new XElement("Start"),

        for(int i = 0; i <= 5; i++)
        {
                         new XElement("Entry", 
                             new XAttribute("Address", "0123"),
                             new XAttribute("default", "0"),

                        new XElement("Descripion", "here is the description"),

                        new XElement("Data", "Data goes here ")

                );

            }
        );

        }

2 个答案:

答案 0 :(得分:7)

您目前正在尝试在语句中间使用for循环。那不行。

选项:

  • 使用Enumerable.Range创建一系列值,然后使用Select对其进行转换:

    XDocument myDoc = new XDocument(
        new XDeclaration("1.0" ,"utf-8","yes"),
        // Note that the extra elements are *within* the Start element
        new XElement("Start",
            Enumerable.Range(0, 6)
                      .Select(i => 
                           new XElement("Entry", 
                               new XAttribute("Address", "0123"),
                               new XAttribute("default", "0"),
                               new XElement("Descripion", "here is the description"),
                               new XElement("Data", "Data goes here ")))
    );
    
  • 首先创建文档,然后在循环中添加元素

    XDocument myDoc = new XDocument(
        new XDeclaration("1.0" ,"utf-8","yes"),
        new XElement("Start"));
    for (int i = 0; i <= 5; i++) 
    {
        myDoc.Root.Add(new XElement("Entry",
                           new XAttribute("Address", "0123"),
                           new XAttribute("default", "0"),
                           new XElement("Descripion", "here is the description"),
                           new XElement("Data", "Data goes here "));
    }
    

答案 1 :(得分:0)

使用XML序列化。与IMO合作更容易。

http://support.microsoft.com/kb/815813

相关问题