How would i iterate of each child of child Nodes and Display its Element Name and attribute Value RRS feed

  • Question

  • User45893093 posted

    I Have some Sample Data XML,

                        <oval-res:definition definition_id="oval:com.rapid7.oval:def:5004" version="1" result="true">
                             <oval-res:criteria operator="OR" negate="false" result="true">
                                     <oval-res:criterion test_ref="oval:com.rapid7.oval:tst:50041" version="1" negate="false" result="true"/>
                                     <oval-res:criterion test_ref="oval:com.rapid7.oval:tst:50042" version="1" negate="false" result="false"/>
                                     <oval-res:criterion test_ref="oval:com.rapid7.oval:tst:50043" version="1" negate="false" result="false"/>
                                     <oval-res:criterion test_ref="oval:com.rapid7.oval:tst:50044" version="1" negate="false" result="false"/>
                        <oval-res:definition definition_id="oval:com.rapid7.oval:def:7182" version="1" result="true">
                                     <oval-res:criteria operator="AND" negate="false" result="true">
                                     <oval-res:criterion test_ref="oval:com.rapid7.oval:tst:7281" version="1" negate="false" result="true"/>
                                     <oval-res:extend_definition definition_ref="oval:com.rapid7.oval:def:5004" version="1" negate="false" result="true"/>

    Suppose i want to get the attribute Values of <oval-res:definition></oval-res:definition> and <oval-res:criterion></oval-res:criterion>

    XDocument xdoc = XDocument.Load(filepath);
    IEnumerable<XElement> records = xdoc.Descendants("oval-res:results");//Rule
    The above throws me Exception in "oval-res:results" 

    I Managed to get attribute values in this way,..

    string outputDirectory = @"C:\Users\Public\TestFolder";//Directory path where you want to save the output txt file
                if (!System.IO.Directory.Exists(outputDirectory))
                string outputfileName1 = DateTime.Now.ToString("yyyy_MM_dd") + @"-definition.txt";
                string filepath = @"C:\Users\Kir@n\Desktop\ConsoleApplication1\linux_arf.xml";
                XmlDocument doc = new XmlDocument();
                if (!(doc == null))
                        XmlNodeList elemList = doc.GetElementsByTagName(@"oval-res:definition");
                        using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputDirectory + @"\" + outputfileName1))
                            file.WriteLine(string.Format("{0}|{1}|{2}|", "definition_id", "version", "result"));
                            for (int i = 0; i < elemList.Count; i++)
                                string def_id = elemList[i].Attributes["definition_id"].Value;
                                if (def_id != null)
                                    def_id = def_id.Replace("\n", "\\n");
                                string version = elemList[i].Attributes["version"].Value;
                                if (version != null)
                                    version = version.Replace("\n", "\\n");
                                string result = elemList[i].Attributes["result"].Value;
                                if (result != null)
                                    result = result.Replace("\n", "\\n");
                                Console.WriteLine(def_id + "  |  " + version + "  |  " + result + "  |  ");
                                file.WriteLine(string.Format("{0}|{1}|{2}|", def_id, version, result));
                    catch (Exception ex)

    But, i would like to know how do we achieve this throgh proper Descendants and iterating through its child elements and getting its values !!
    Thursday, November 12, 2015 2:07 AM


  • User-271186128 posted

    Hi Deamon_Dagger,

    Welcome to asp.net forum.


    How would i iterate of each child of child Nodes and Display its Element Name and attribute Value

    As for this issue, you could try to use nested foreach statement or for statement. Here is a sample, you could refer to it:

    Code in xml file:

    <?xml version="1.0" encoding="utf-8" ?>
      <Question id="1" type='SingleChoice'>
        <Text>Where is your project primarily located? (select only one)</Text>
          <Answer id="1"> In an urbanized area</Answer>
          <Answer id="2"> In a metropolitan area outside of core urbanized area </Answer>
          <Answer id="3"> In a small city/town</Answer>
          <Answer id="4"> In a rural area</Answer>
      <Question id="2" type='SingleChoice'>
        <Text>What neighborhood is the project located in? (select only one)</Text>
          <Answer id="1">Primarily a residential area</Answer>
          <Answer id="2">Primarily an employment area</Answer>
          <Answer id="3">Primarily an industrial/warehousing area</Answer>

    Code in page (.aspx.cs)

            protected void Page_Load(object sender, EventArgs e)
                XmlDocument xml = new XmlDocument();
                StringBuilder sb = new StringBuilder();
                List<DiagnosticTool> queslist = new List<DiagnosticTool>();
                XmlNodeList list = xml.SelectNodes("/Questions/Question");
                foreach (XmlNode xn in list)
                    DiagnosticTool dt = new DiagnosticTool();
                    dt.QuestionId = Convert.ToInt32(xn.Attributes["id"].Value); //Get Question Id                
                    dt.QuestionType = xn.Attributes["type"].Value;  //Get Question Type
                    dt.Text = xn["Text"].InnerText; //Get Text Node
                    sb.AppendLine("<br />");
                    List<Answer> answerlist = new List<Answer>();
                    XmlNodeList list2 = xn.SelectNodes(".//Answers/Answer");
                    foreach (XmlNode xn2 in list2)
                        Answer an = new Answer();
                        an.AnswerId = Convert.ToInt32(xn2.Attributes["id"].Value);//Get answer id.
                        an.Text = xn2.InnerText;//Get answer node.
                        answerlist.Add(an); //add answer to List
                        sb.AppendLine("<br />");
                    dt.Answers = answerlist;
                    queslist.Add(dt); // Add question to list
                    sb.AppendLine("<br />");

    Code in class:

        public class DiagnosticTool
            public string Text { get; set; }
            public IList<Answer> Answers { get; set; }
            public int QuestionId { get; set; }
            public string QuestionType { get; set; }
        public class Answer
            public int AnswerId { get; set; }
            public string Text { get; set; }

    The output:

    1 SingleChoice Where is your project primarily located? (select only one) 
     1 In an urbanized area 
     2 In a metropolitan area outside of core urbanized area 
     3 In a small city/town 
     4 In a rural area 
     2 SingleChoice What neighborhood is the project located in? (select only one) 
     1 Primarily a residential area 
     2 Primarily an employment area 
     3 Primarily an industrial/warehousing area 

    Best regards,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 12, 2015 4:21 AM