如何使用for循环添加元素来编写XML文件

时间:2019-07-15 08:08:17

标签: c# xml

我有一个文件列表框。所以我想将此列表的项目添加到XML元素中。 但是,我在处理将项目添加到XML的循环时遇到问题。

//My goal:

//<project>
       <drawing>
//        file1 
//        file2
//    <drawing/>
//<project>
//I tried to add items to element 

//however it looks like

<drawing> file1file2 </drawing>

   List<string> drawingList = new List<string>();

   drawingList.Add(listBox1.Items[i].ToString());

    new XDocument(
                        new XElement("Project",
                            new XElement("Name", project.name),
                            new XElement("Path", project.path),
                            new XElement("Drawing", drawingList)
                        )
                    )
                    .Save(@"C:\Users\for\Desktop\abc1.cadiprj");
);




2 个答案:

答案 0 :(得分:0)

请参见下面的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication120
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            List<string> drawingList = new List<string>() { "file1", "file2", "file3", "file4"};

            XDocument doc = new XDocument(
                new XElement("Project",
                    new XElement("Name", "abc"),
                    new XElement("Path", @"c:\temp\"),
                     new XElement("Drawing")
                )
           );
            XElement xDrawing = doc.Descendants("Drawing").FirstOrDefault();

            foreach (string drawing in drawingList)
            {
                xDrawing.Add(new XElement("Drawing", drawing));
            }
        }
    }

}

答案 1 :(得分:0)

要实现以不同行分隔的文件,您可以{#1}}以裸线作为分隔符

string.Join()

这将为您提供此输出

List<string> drawingList = new List<string>() { "file1", "file2"};

XDocument doc = new XDocument(
    new XElement("Project",
        new XElement("Name", "abc"),
        new XElement("Path", @"c:\temp\"),
         new XElement("Drawing", string.Join("\n", drawingList.ToArray()))
    )
);

作为建议,我建议使用一种不固定的格式,恕我直言:

<Project>
    <Name>abd</Name>
    <Path>your path</Path>
    <Drawing>
        file1
        file2
    </Drawing>
</Project>