Search code examples
.netxmlc#-4.0xml-parsingwindows-services

Loading XML child nodes value in variables in C#


I want the xml child nodes value in individual variable. The root node is 'Parent" and the main node is 'Reports'. I have written a looping statement for each main node 'Reports' and to extract the values of the child nodes.

I am able to load the xml(with values) in loop but fetches the below error while assigning the child nodes value to avariable.

"An unhandled exception of type 'System.NullReferenceException' occurred in project.exe"

c# code

 public Service1()
        {
            InitializeComponent();

            foreach (string file in Directory.EnumerateFiles(Project.Constants.PATHNAME, "*.xml"))
            {
                XElement ReportData = XElement.Load(file);
                var Reportinfo = ReportData.Elements("Reports");
                foreach (var Reports in Reportinfo.Nodes())
                {
                    var ReportName = Reports.Document.Element("ReportName").Value;
                    var DBExecution = Reports.Document.Element("DBExecution").Value;
                    var DBName = Reports.Document.Element("DBName").Value;
                }

                var obj = new DatabaseAction("connection1");
                var result = obj.ExecuteCommandQuery("select * from sometable");

            }

        }

Here is the xml:

<?xml version="1.0" encoding="utf-8"?>
<Parent>
<Reports name="Report1">
  <ReportName>xzy</ReportName>
  <DBExecution>Yes</DBExecution>
  <DBName>sqldb0001</DBName>
  <OutputFileName>xyz_output</OutputFileName>
  <OutputFilePath>123</OutputFilePath>
</Reports>
<Reports name="Report2">
  <ReportName>asdf</ReportName>
  <DBExecution>false</DBExecution>
  <DBName>sqldb0002231</DBName>
  <OutputFileName>xyzasdf_output</OutputFileName>
  <OutputFilePath>123333</OutputFilePath>
</Reports>
</Parent>

Please let me know where i go wrong? Thanks


Solution

  • Here is your solution. It shows how to iterate through the Reports fragments and get individual child elements values in a loop.

    c#

    void Main()
    {
        const string file = @"e:\Temp\Manivannan.xml";
    
        string ReportName = string.Empty;
        string DBExecution = string.Empty;
        string DBName = string.Empty;
    
        XDocument ReportData = XDocument.Load(file);
        foreach (var Reports in ReportData.Descendants("Reports"))
        {
            ReportName = Reports.Element("ReportName").Value;
            DBExecution = Reports.Element("DBExecution").Value;
            DBName = Reports.Element("DBName").Value;
        }
    }