So I would like to get a NodeList from a specific node. I'm writing a program which replicates a bank as a form of "final" in this course and I've written an XML document which contains all clients for my bank. I've written code for a log-in function and now I want to return the specific clients details.

        <name>Victor Olin</name>
          <name>Victors Sparkonto</name>
          <name>Victors Lönekonto</name>

So the wanted result is that I would like a NodeList containing all "savingsAcc" and "regularAcc" this specific client have so I can access all the inner texts and send them to the client. When the client logs in with correct credentials, the correct client is specified and I think that node can act as a root element but I'm not sure on how to implement it.

1 Answers

jdweng On Best Solutions

Using Xml Linq :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
    class Program
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
            XDocument doc = XDocument.Load(FILENAME);

            foreach (XElement client in doc.Descendants("client"))
                Client newClient = new Client();

       = (string)client.Element("name");
                newClient.ssid = (string)client.Element("ssid");
                newClient.pswd = (string)client.Element("pswd");

                List<XElement> xAccounts = client.Elements().Where(x => (x.Name.LocalName == "savingsAcc") || (x.Name.LocalName == "regularAcc")).ToList();
                foreach (XElement xAccount in xAccounts)
                    Account newAccount = null;
                    switch (xAccount.Name.LocalName)
                        case "savingsAcc" :
                            newAccount = new SavingsAccount();
                        case "regularAcc":
                            newAccount = new RegularAccount();

           = (string)xAccount.Element("name");
                    newAccount.accountNumber = (string)xAccount.Element("accountNumber");
                    newAccount.balance = (decimal)xAccount.Element("balance");
    public class Client
        public static List<Client> clients = new List<Client>();
        public string name { get; set; }
        public string ssid { get; set; }
        public string pswd { get; set; }
        public List<Account> accounts = new List<Account>();
    public class Account
        public string name { get; set; }
        public string accountNumber { get; set; }
        public decimal balance { get; set; }
    public class SavingsAccount : Account 
    public class RegularAccount : Account