locked
how to create a function for xml string RRS feed

  • Question

  • User569149469 posted
    using System;
    using System.Collections.Generic;
    
    public class Folders
    {
        public static IEnumerable<string> FolderNames(string xml, char startingLetter)
        {
            throw new NotImplementedException("Waiting to be implemented.");
        }
    
        public static void Main(string[] args)
        {
            string xml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<folder name=\"c\">" +
                    "<folder name=\"program files\">" +
                        "<folder name=\"uninstall information\" />" +
                    "</folder>" +
                    "<folder name=\"users\" />" +
                "</folder>";
    
            foreach (string name in Folders.FolderNames(xml, 'u'))
                Console.WriteLine(name);
        }
    }

    Implement a function FolderNames, which accepts a string containing an XML file that specifies folder structure and returns all folder names that start with startingLetter. The XML format is given in the example below.
    For example, for the letter 'u' and XML file: <?xml version="1.0" encoding="UTF-8"?> <folder name="c"> <folder name="program files"> <folder name="uninstall information" /> </folder> <folder name="users" /> </folder>

    Saturday, August 18, 2018 6:10 AM

All replies

  • User1724605321 posted

    Hi phmaspnet,

    Code below is for your reference :

     public static List<string> FolderNames(string xml, string startingLetter)
            {
                List<string> list = new List<string>();
                XDocument doc = XDocument.Parse(xml);
    
                var namelist = doc.Descendants("folder")
                                   .Where(field => ((string)field.Attribute("name")).StartsWith(startingLetter))
                                   .Select(field => new
                                   {
                                       name = (string)field.Attribute("name")
    
                                   }).ToList();
    
    
    
                foreach (var item in namelist)
                {
                    list.Add(item.name);
                }
           
    
    
                return list;
            }
    
            static void Main(string[] args)
            {
                string xml =
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<folder name=\"c\">" +
                    "<folder name=\"program files\">" +
                        "<folder name=\"uninstall information\" />" +
                    "</folder>" +
                    "<folder name=\"users\" />" +
                "</folder>";
               
                var result= FolderNames(xml,"u");
    
            }

    Best Regards,

    Nan Yu

    Monday, August 20, 2018 6:13 AM