需要使用 C# 在现有 XML 文件下添加新项目

问题描述

我需要使用 C# 在现有文件添加新项目,请提供使用 C# 执行此操作的最佳逻辑。 下面是我的 XML 文件(输入)=

<?xml version="1.0" encoding="UTF-8"?>
<FileSetting xmlns="http://ltsc.ieee.org/xsd/LOM" xmlns:xs="http://www.M1.org/2001/XMLSchema">
   <Files>
      <File Section="Section 1" Method="Complete" Location="Total 1">
         <Columns>
            <Profile Method="DataCollection" Item="All" />
         </Columns>
      </File>
      <!--  <File Section="Section 2" Method="Complete" Location="Total 2">
    <Columns>
      <Profile Method= "DataCollection" Item="All"/>
     </Columns>
  </File> -->
      <File Section="Section 3" Method="Complete" Location="Main">
         <Columns>
            <Profile Method="DataCollection" Item="All" />
         </Columns>
      </File>
   </Files>
</FileSetting>

在我现有的 XML 文件中,我想在文件添加新的文件项,所以 我期待输出为=

<?xml version="1.0" encoding="UTF-8"?>
<FileSetting xmlns="http://ltsc.ieee.org/xsd/LOM" xmlns:xs="http://www.M1.org/2001/XMLSchema">
   <Files>
      <File Section="Section 1" Method="Complete" Location="Total 1">
         <Columns>
            <Profile Method="DataCollection" Item="All" />
         </Columns>
      </File>
      <!--  <File Section="Section 2" Method="Complete" Location="Total 2">
    <Columns>
      <Profile Method= "DataCollection" Item="All"/>
     </Columns>
  </File> -->
      <File Section="Section 3" Method="Complete" Location="Main">
         <Columns>
            <Profile Method="DataCollection" Item="All" />
         </Columns>
      </File>
      <File Section="Section 4" Method="NotComplete" Location="Test5">
         <Columns>
            <Profile Method="DataCollecter" Item="Partial" />
         </Columns>
      </File>
   </Files>
</FileSetting>

谁能提供最好的逻辑来在 C# 中做到这一点?

提前致谢

解决方法

使用 xml linq :

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

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            XNamespace ns = doc.Root.GetDefaultNamespace();

            XElement files = doc.Descendants(ns + "Files").FirstOrDefault();

            XElement newFile = new XElement(ns + "File",new object[] {
                new XAttribute("Section","Section 4"),new XAttribute("Method","NotComplete"),new XAttribute("Location","Test5"),new XElement(ns + "Columns",new object[] {
                    new XElement("Profile",new object[] {
                        new XAttribute("Method","DataCollecter"),new XAttribute("Item","Partial")
                    })
                })
            });

            files.Add(newFile);
        }
    }
}