0

i have an xml document like the below

 <?xml version='1.0'?>
<ENVELOPE>
<HEADER>
    <TALLYREQUEST>Import Data</TALLYREQUEST>
</HEADER>
<BODY>
    <IMPORTDATA>
        <REQUESTDESC><REPORTNAME>All Masters</REPORTNAME><STATICVARIABLES><SVCURRENTCOMPANY>MSIT</SVCURRENTCOMPANY></STATICVARIABLES></REQUESTDESC>
        <REQUESTDATA>
            <TALLYMESSAGE>
<Entry_x0020_NO.>125</Entry_x0020_NO.>
<DATE>12</DATE>
<GUID>1258</GUID>
<NARRATION>1542</NARRATION>
<VOTURETYPENAME>456</VOTURETYPENAME>
<NAME>achuth</NAME>
<AMOUNT>250</AMOUNT>
  </TALLYMESSAGE>
        </REQUESTDATA>
    </IMPORTDATA>
</BODY>
</ENVELOPE>

in which i need to get the inner node tally Message and its children inner text values using c# code in a loop and make each node as excel sheet column name and the values as row values in excel. the error is below error is null reference

Achuth hadnoor
  • 332
  • 4
  • 16

1 Answers1

1

You could do this, solution uses Linq to Xml.

    XDocument doc = XDocument.Load(filename);

    var messages = doc.Descendants("TALLYMESSAGE").Select(s=> new {
        Entry =  s.Element("Entry_x0020_NO.").Value,
        DATE =  s.Element("DATE").Value,
        GUID =  s.Element("GUID").Value,
        NARRATION =  s.Element("NARRATION").Value,
        VOTURETYPENAME =  s.Element("VOTURETYPENAME").Value,
        AMOUNT =  s.Element("AMOUNT").Value,
        NAME =  s.Element("NAME").Value,

    }).ToList();

Update : As asked in comments, if you are looking to loop through each elements you could do this.

    foreach(var element in doc.Descendants("TALLYMESSAGE").Elements()) 
    {
        Console.WriteLine("{0} = {1}", element.Name, element.Value);
    }

Check this Example

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35