I have a complex XML file where I want to retrieve different values from the different Set tag.At the end, i need to take the values to a CSV file.
Please see the xml file format
I am trying to retrieve the value of
<szItemID>3268750004533</szItemID> from the first set
<lMerchandiseStructureID>40</lMerchandiseStructureID> from the second set
<szDesc>PHG VIANDE SECHEE DE</szDesc> from the third set
<dPackingUnitPriceAmount>75</dPackingUnitPriceAmount> from the fourth tag
I have tried to retrieve the first element through the below code but getting an error
NullReferenceException was unhandled Object reference not set to an instance of an object
Code
XmlDocument document = new XmlDocument();
document.Load(@"D:\\xml_1.xml");
string myXmlString = document.OuterXml.ToString();
XElement xml = XElement.Parse(myXmlString);
Console.WriteLine(string.Format("{0}",xml.XPathSelectElement("/UpdateDB/Transaction/Insert/Set/szItemID").Value));
Please help
StringBuilder dataToBeWritten = new StringBuilder();
var doc = XDocument.Load(@"D:\xml_2.xml");
foreach (var trans in doc.Descendants("Transaction"))
{
var val3 = (string)doc.Descendants("Set").Elements("szItemID").First();
var val4 = (string)doc.Descendants("Set").Elements("lMerchandiseStructureID").First();
var val5 = (string)doc.Descendants("Set").Elements("szName").First();
var val6 = (string)doc.Descendants("Set").Elements("lRetailStoreID").First();
var val7 = (string)doc.Descendants("Set").Elements("bIsContract").First();
dataToBeWritten.Append(val3);
dataToBeWritten.Append(",");
dataToBeWritten.Append(val4);
dataToBeWritten.Append(",");
dataToBeWritten.Append(val5);
dataToBeWritten.Append(",");
dataToBeWritten.Append(val6);
dataToBeWritten.Append(",");
dataToBeWritten.Append(val7);
dataToBeWritten.Append(",");
dataToBeWritten.Append(Environment.NewLine);
}
Console.WriteLine(dataToBeWritten.ToString());
Console.ReadLine();
var testpath = @"D:\\Lutchmee2.csv";
File.WriteAllText(testpath, dataToBeWritten.ToString());