【发布时间】:2017-04-08 17:22:00
【问题描述】:
我正在开发一个工具,并且我正在使用一个 XML 配置文件,我需要以编程方式添加配置项。我正在使用 .Net Core,并且我一直使用 this question 作为我的工作指南,但下面的部分似乎有效,但没有示例中列出的成员函数。
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
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 的 List 并且我可以通过这种方式获取最后一个节点,然后追加,但仍然存在 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();