我正在使用一个工具,并且正在使用一个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