我正在使用一個工具,並且正在使用一個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;
您只需要添加ToList():List rows = root.Descendants(「template」)。ToList(); –
jdweng