Parsing XML rows using script Component

599 Views Asked by At

I have a flat file and the data is stored in XML rows. I am parsing the XML rows using a script component as source as below. It's working fine, until in a particular row, we don't see one of the columns.

For example: on the 12th row of the source file it has only Col1 and Col2 and doesn't have Col3. I need to modify the below C# code so that whenever it doesn't find a column in a row it needs to return as NULL.

public override void CreateNewOutputRows()
{

    string filepath = @"c:\test\test\xmldata.txt";
    string fileContent = new StreamReader(filepath).ReadToEnd();


    XmlDocument doc = new XmlDocument();
    doc.LoadXml("<root>"+ fileContent+"</root>");

    XmlNodeList xnl = doc.GetElementsByTagName("TICKET_EXTRACT");


    foreach (XmlNode xn in xnl) {

        Output0Buffer.AddRow();
        Output0Buffer.col1 = xn["col1"].InnerText;        
        Output0Buffer.col2 = xn["col2"].InnerText;
        Output0Buffer.col3 = xn["col3"].InnerText;
    }
1

There are 1 best solutions below

0
On

You can basically do two things: either use a null conditional operator:

Output0Buffer.col3 = xn["col3"]?.InnerText;

(the right hand side is null if xn["col3"] is null)

or wrap it in an if statement:

if (xn["col3"] != null) {
    Output0Buffer.col3 = xn["col3"].InnerText;
}