2017-04-08 46 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文件中維護磁盤上的文件的元數據。 (試圖讓最終用戶更容易)再次感謝! –