如何解决需要使用 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);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。