Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8900317
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T01:04:44+00:00 2026-06-15T01:04:44+00:00

I have an XML source document with multiple report nodes under the Root node.

  • 0

I have an XML source document with multiple “report” nodes under the Root node. I need to read each “report” node into its own DataTable. It looks like I’ll either need to transform my source XML data using an xsl stylesheet to get it in the format that’ll work nicely or iterate through my xml elements like so:

namespace XmlParse2
{
    class Program
    {
        static IEnumerable<string> expectedFields = new List<string>() { "Field1", "Field2", "Field3", "Field4" };

        static void Main(string[] args)
        {
            string xml = @"<Root>
                             <Report1>
                               <Row>
                                 <Field1>data1-1</Field1>
                                 <Field2>data1-2</Field2>
                                 <Field4>data1-4</Field4>
                               </Row>
                               <Row>
                                 <Field1>data2-1</Field1>
                                 <Field2>data2-2</Field2>
                               </Row>
                             </Report1>
                             <Report2>
                               <Row>
                                 <Field1>data1-1</Field1>
                                 <Field4>data1-4</Field4>
                               </Row>
                               <Row>
                                 <Field1>data2-1</Field1>
                                 <Field3>data2-3</Field3>
                               </Row>
                             </Report2>
                           </Root>";

            DataTable report1 = new DataTable("Report1");
            report1.Columns.Add("Field1");
            report1.Columns.Add("Field2");
            report1.Columns.Add("Field3");
            report1.Columns.Add("Field4");

            DataTable report2 = new DataTable("Report2");
            report2.Columns.Add("Field1");
            report2.Columns.Add("Field2");
            report2.Columns.Add("Field3");
            report2.Columns.Add("Field4");

            var doc = XDocument.Parse(xml);
            var report1Data = doc.Root.Elements("Report1").Elements("Row").Select(record => MapRecord(record));
            var report2Data = doc.Root.Elements("Report2").Elements("Row").Select(record => MapRecord(record));

            report1 = addRows(report1, report1Data);
            report2 = addRows(report2, report2Data);

            Console.ReadLine();
        }

        public static Dictionary<string, string> MapRecord(XElement element)
        {
            var output = new Dictionary<string, string>();
            foreach (var field in expectedFields)
            {
                bool hasField = element.Elements(field).Any();
                if (hasField)
                {
                    output.Add(field, element.Elements(field).First().Value);
                }
            }
            return output;
        }

        public static DataTable addRows(DataTable table, IEnumerable<Dictionary<string, string>> data)
        {
            foreach (Dictionary<string, string> dict in data)
            {
                DataRow row = table.NewRow();

                foreach(var item in dict) 
                {
                    row[item.Key] = item.Value;
                }

                table.Rows.Add(row);
            }

            return table;
        }
    }
}

The problem with my source data not working seems to be that both Report1 and Report2 have child nodes that are named “Row” and my attempts to do stuff using DataSet.ReadXml is not successful because my code just groups all nodes named Row into one DataTable instead of separate DataTables. :/

What am I missing?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T01:04:45+00:00Added an answer on June 15, 2026 at 1:04 am
    XDocument xdoc = XDocument.Load(path_to_xml);
    var tables = xdoc.Root.Elements()
                     .Select(report => {
                         DataTable table = new DataTable(report.Name.LocalName);
                         var fields = report
                                .Descendants("Row")
                                .SelectMany(row => row.Elements()
                                                      .Select(e => e.Name.LocalName))
                                .Distinct();
    
                         foreach(string field in fields)
                             table.Columns.Add(field);
    
                         foreach(var row in report.Descendants("Row"))
                         {
                             DataRow dr = table.NewRow();
                             foreach(var field in row.Elements())
                                 dr[field.Name.LocalName] = (string)field;
                             table.Rows.Add(dr);
                         }                                   
    
                         return table;
                    });
    

    This query will return IEnumerable<DataTable>. Each datatable will contain only those columns, which have values in xml. Column names retrieved from xml and could be different for each table. For your sample structure will look this way:

    DataTable: Report1
      Columns: Field1, Field2, Field4
    
    DataTable: Report2
      Columns: Field1, Field3, Field4
    

    All rows data will be added to each table.


    You can extract some code to methods. It will make code easier to understand:

    XDocument xdoc = XDocument.Load(path_to_xml);
    var tables = xdoc.Root.Elements()
                     .Select(report => CreateTableFrom(report));
    

    And methods:

    private static DataTable CreateTableFrom(XElement report)
    {
        DataTable table = new DataTable(report.Name.LocalName);
        table.Columns.AddRange(GetColumnsOf(report));
    
        foreach (var row in report.Descendants("Row"))
        {
            DataRow dr = table.NewRow();
            foreach (var field in row.Elements())
                dr[field.Name.LocalName] = (string)field;
            table.Rows.Add(dr);
        }
    
        return table;
    }
    
    private static DataColumn[] GetColumnsOf(XElement report)
    {
        return report.Descendants("Row")
                     .SelectMany(row => row.Elements().Select(e => e.Name.LocalName))
                     .Distinct()
                     .Select(field => new DataColumn(field))
                     .ToArray();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have document source in XML. I need to generate PDF and HTML pages
Have a source xml document that uses namespace containing prefixes and a default namespace.
Using this source document: <?xml version=1.0 encoding=UTF-8?> <Root> <Element1 id=UniqueId1> <SubElement1/> <SubElement2> <LeafElement1/> <LeafElement1/>
I'm trying to combine multiple, smaller XML files into one large XML. I have
I have a source document with XML structure similar to this: <FOO> <BAR>x</BAR> <BAR>y</BAR>
I have been using XML comments to document my source code in VB.Net (and
I have an xml document: <?xml version=1.0 encoding=utf-8?> <Root> <Child name=MyType compareMode=EQ></Child> </Root> And
I need to transform one XML document into another using XSLT (for now from
I have a source XHTML document with elements in multiple namespaces that I am
I have a XSLT which will split large xml file into multiple xml file

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.