2017-04-08 45 views
0

我正在使用一个工具,并且正在使用一个XML配置文件,我需要以编程方式添加配置项目。我使用的是.Net Core,并且我一直在使用this question作为我的工作的指导,但看起来下面的部分工作正常,但没有示例中列出的成员函数。附加XML .NET核心(控制台)

IEnumerable<XElement> rows = root.Descendants("Student"); 

下面是从我试图用我自己的目的原题示例代码:

XDocument xDocument = XDocument.Load("Test.xml"); 
XElement root= xDocument.Element("School"); 
IEnumerable<XElement> rows = root.Descendants("Student"); 
XElement firstRow= rows.First(); 
firstRow.AddBeforeSelf(
    new XElement("Student", 
    new XElement("FirstName", firstName), 
    new XElement("LastName", lastName))); 
xDocument.Save("Test.xml"); 

原来的示例代码中使用是应该为IEnumerable <的XElement>对象有一个.first,我希望有一个.last函数返回文档中的第一个条目。问题是Visual Studio中不允许我要么使用,这是一个部分我写的函数:

XDocument xD = XDocument.Load(_config); 
XElement root = xD.Element("Store"); 
List<XElement> rows = root.Descendants("template"); 
XElement[] arr = rows.ToArray(); 
arr[arr.Length - 1].AddAfterSelf(
new XElement("template"), 
new XElement("filePath", tmp.TempPath), 
new XElement("Name", tmp.TempName), 
new XElement("description", tmp.TempDesc)); 

后来改的XElement的名单<>,我可以得到最后的节点,然后追加,但仍然存在root.Descendants()调用仅返回IEnumerable的问题。

这里是我的using语句:

using System; 
using System.Data.SqlClient; 
using System.IO; 
using System.Xml; 
using System.Collections.Generic; 
using System.Xml.Linq; 
+0

您只需要添加ToList():List rows = root.Descendants(“template”)。ToList(); – jdweng

回答

1

我个人认为这个配置文件应该是只读的,如果有,你需要存储的应用价值,你应该将它们存储在一个单独文件。

说了这么多,要解决你的问题,你需要添加System.Linq命名空间。

using System.Linq; 

First()Last()等是Linq方法。

+0

尽管我明白不需要写配置文件,但我希望让用户能够让程序至少生成一个初始的内部配置。我想到的情况实际上是为了让应用程序在xml文件中维护磁盘上的文件的元数据。 (试图让最终用户更容易)再次感谢! –