简体   繁体   English

附加XML .NET Core(控制台)

[英]Appending XML .NET Core (Console)

I'm working on a tool, and I'm using an XML configuration file, that I need to add configuration items to programmatically. 我正在使用工具,并且正在使用XML配置文件,我需要以编程方式添加配置项。 I'm using .Net Core, and I've been using this question as a guide for my work, but it appears that the part with below works, but doesn't have a member function as listed in the example. 我正在使用.Net Core,并且一直在用这个问题作为我工作的指南,但是看起来下面的部分可以用,但是没有示例中列出的成员函数。

IEnumerable<XElement> rows = root.Descendants("Student");

Here is the Sample code from the original question that I'm attempting to use for my own purposes: 这是我出于自身目的尝试使用的原始问题的示例代码:

 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");

The original sample code used an IEnumerable < XElement > object that is supposed to have a .first, and I'm hoping has a .last function that returns the first entry in the document. 原始示例代码使用了一个IEnumerable <XElement>对象,该对象应该具有一个.first,我希望具有一个.last函数,该函数返回文档中的第一个条目。 The issue is Visual Studio doesn't allow me to use either, and this is a partial of the function I'm writing: 问题是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));

I changed over to a List<> of XElement and I can get the last node that way, and append after, but there's still the issue that the root.Descendants() call wants to return the IEnumerable<> only. 我切换到XElement的List <>,我可以以这种方式获取最后一个节点,然后追加,但是仍然存在问题,root.Descendants()调用只想返回IEnumerable <>。

Here are my using Statements: 这是我的使用声明:

using System;
using System.Data.SqlClient;
using System.IO;
using System.Xml;
using System.Collections.Generic;
using System.Xml.Linq;

Personally I think that config files should be read-only, and if there are values that you need to store for the application, you should store them in a separate file. 我个人认为配置文件应该是只读的,并且如果需要为应用程序存储值,则应将它们存储在单独的文件中。

Having that said, to solve your problem, you need to add System.Linq namespace. 话虽如此,要解决您的问题,您需要添加System.Linq命名空间。

using System.Linq;

First() , Last() etc. are Linq methods. First()Last()等是Linq方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM