CSV using XmlNode

 To create a CSV from an XmlNode in C#, you can follow these steps:


1. Parse the XML structure using XmlNode.



2. Extract the data you need from child nodes.



3. Write the CSV content using a StringBuilder or directly with StreamWriter.




Here's a sample code snippet:


using System;

using System.IO;

using System.Text;

using System.Xml;


public class XmlToCsvConverter

{

    public static void ConvertXmlNodeToCsv(XmlNode rootNode, string csvFilePath)

    {

        StringBuilder csvContent = new StringBuilder();


        // Assuming all child nodes have the same structure

        // Add header

        if (rootNode.HasChildNodes)

        {

            XmlNode firstRow = rootNode.FirstChild;

            for (int i = 0; i < firstRow.ChildNodes.Count; i++)

            {

                csvContent.Append(firstRow.ChildNodes[i].Name);

                if (i < firstRow.ChildNodes.Count - 1)

                    csvContent.Append(",");

            }

            csvContent.AppendLine();

        }


        // Add rows

        foreach (XmlNode row in rootNode.ChildNodes)

        {

            for (int i = 0; i < row.ChildNodes.Count; i++)

            {

                string value = row.ChildNodes[i].InnerText.Replace(",", " "); // escape commas

                csvContent.Append(value);

                if (i < row.ChildNodes.Count - 1)

                    csvContent.Append(",");

            }

            csvContent.AppendLine();

        }


        // Write to file

        File.WriteAllText(csvFilePath, csvContent.ToString());

    }

}


Example XML:


<Employees>

  <Employee>

    <Name>John Doe</Name>

    <Age>30</Age>

    <Department>HR</Department>

  </Employee>

  <Employee>

    <Name>Jane Smith</Name>

    <Age>25</Age>

    <Department>IT</Department>

  </Employee>

</Employees>


Usage:


XmlDocument doc = new XmlDocument();

doc.Load("employees.xml");

XmlNode root = doc.DocumentElement;


XmlToCsvConverter.ConvertXmlNodeToCsv(root, "e

mployees.csv");


Would you like a version that works with nested XML as well?


---

var config = new ConfigurationBuilder()

    .AddJsonFile("appsettings.json")

    .Build();


var jobSettings = config.GetSection("JobSettings").Get<JobSettings>();


if (jobSettings.IsJobEnabled &&

    Enum.TryParse<DayOfWeek>(jobSettings.RunDay, out var runDay) &&

    DateTime.Today.DayOfWeek == runDay)

{

    Console.WriteLine("Running weekly job...");

    // Run your job here

}

else

{

    Console.WriteLine("Job is disabled or not scheduled for today.");

}

Model---

public class JobSettings

{

    public bool IsJobEnabled { get; set; }

    public string RunDay { get; set; 

}

}


App setting 

{

  "JobSettings": {

    "IsJobEnabled": true,

    "RunDay": "Sunday"

  }

}

Comments

Popular posts from this blog

String Program in C#

Controller_Model. cs