【问题标题】:Appending XML .NET Core (Console)附加 XML .NET Core(控制台)
【发布时间】: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 对象,该对象应该有一个 .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 的 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();

标签: c# xml .net-core


【解决方案1】:

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

话虽如此,要解决您的问题,您需要添加 System.Linq 命名空间。

using System.Linq;

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

【讨论】:

  • 虽然我确实理解不需要编写配置文件,但我希望用户能够让程序至少生成一个初始的内部配置。我想到的情况实际上是关于应用程序在 xml 文件中维护的磁盘上文件的元数据。 (试图让最终用户更轻松。)再次感谢!
猜你喜欢
  • 2016-12-07
  • 2018-09-13
  • 2018-11-16
  • 1970-01-01
  • 2018-04-19
  • 2022-07-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
相关资源
最近更新 更多