0

I'm working on a tool, and I'm using an XML configuration file, that I need to add configuration items to programmatically. 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.

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. The issue is Visual Studio doesn't allow me to use either, and this is a partial of the function I'm writing:

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.

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;
Community
  • 1
  • 1
Chris Rutherford
  • 1,592
  • 3
  • 22
  • 58

1 Answers1

1

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.

using System.Linq;

First(), Last() etc. are Linq methods.

Ignas
  • 4,092
  • 17
  • 28
  • While I do understand the need to not write config files, I'd like to have users be able have the program generate at least an initial, internal configuration. The situation I have in mind is actually for metadata about files on the disk that the application maintains in the xml file. (trying to make things easier for the end user.) Thanks again! – Chris Rutherford Apr 08 '17 at 19:24