locked
parsing xml nodes into a string[] RRS feed

  • Question

  • User683176063 posted

    I have 

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

    I am trying to read it into a string array like this

    string[] myList = new string[3];// { "c", "program files", "uninstall information", "users" };

    here is what i tried 

    XmlDocument doc = new XmlDocument();
    XmlNodeList elemList = doc.GetElementsByTagName("folder name");
    string[] myList = new string[3];// { "urown", "uall", "uun" };
    IEnumerator ienum = elemList.GetEnumerator();

    while (ienum.MoveNext())
    {
    int i = 0;
    XmlNode foldername = (XmlNode) ienum.Current;

    Console.WriteLine(foldername.InnerText);


    }

    Monday, November 6, 2017 9:16 PM

All replies

  • User2103319870 posted

    merrittr

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

    This code will generate an invalid XML like below and this cannot be parsed to xml in c#

    <?xml version="1.0" encoding="UTF-8"?>
    <folder_name="c">
      <folder_name="program files">
        <folder_name="uninstall information" />
      </folder>
      <folder_name="users" />
    </folder>

    However if your xml is like below , then you can use below codes

    <?xml version="1.0" encoding="UTF-8"?>
    <folder _name="c">
      <folder _name="program files">
        <folder _name="uninstall information" />
      </folder>
      <folder _name="users" />
    </folder>

    Code to Read XML

       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>";
    
                //parse XML string
                XDocument xmldocument = XDocument.Parse(xml);
    
                //Read the values from xml and assign to array
                string[] myList = xmldocument.Descendants().Select(element => element.Attribute("_name").Value).ToArray();

    You also need to make sure you have following using in your page

    using System;
    using System.Xml;
    using System.Linq;
    using System.Xml.Linq;
    Monday, November 6, 2017 9:42 PM