Console App Task 07: Create an XML file using a DTO (Data Transfer Object) in C# ?
Here’s how you can create an XML file using a DTO (Data Transfer Object) in C#:
Step 1: Create a DTO Class
public class TestSettingsDTO
{
public string TestExecutor { get; set; } = "Dynomerk.ChassisDyno.TestExecutor.v1.0.exe";
public string MonthDataDuration { get; set; } = "";
public string OldDataDuration { get; set; } = "";
public string DataTransferLogsPath { get; set; } = "Output\\Log\\DataTransferLogs";
public string SourcePath { get; set; } = @"E:\User\Test Result";
public string ThreeMonthDataPath { get; set; } = @"E:\User\Three_Month_Test_Result_Data";
public string OldDataPath { get; set; } = @"E:\User\Old_Test_Result_Data";
}
Step 2: Generate and Save XML
using System;
using System.Xml.Linq;
class Program
{
static void Main()
{
// Create DTO object
TestSettingsDTO settings = new TestSettingsDTO();
// Create XML using XDocument
XDocument xmlDoc = new XDocument(
new XElement("BasicSettings",
new XElement("TestExecutor", new XAttribute("TestExecutor", settings.TestExecutor)),
new XElement("TestSummaryBKPSettings",
new XElement("Settings", new XAttribute("MonthDataDuration", settings.MonthDataDuration)),
new XElement("Settings", new XAttribute("OldDataDuration", settings.OldDataDuration)),
new XElement("Settings",
new XAttribute("DataTransferLogsPath", settings.DataTransferLogsPath),
new XAttribute("SourcePath", settings.SourcePath),
new XAttribute("ThreeMonthDataPath", settings.ThreeMonthDataPath),
new XAttribute("Old_DataPath", settings.OldDataPath)
)
)
)
);
// Save XML file
string filePath = @"C:\path\to\your\settings.xml"; // Change to desired path
xmlDoc.Save(filePath);
Console.WriteLine("XML File Created Successfully at " + filePath);
}
}
Generated XML Output
<BasicSettings>
<TestExecutor TestExecutor="Dynomerk.ChassisDyno.TestExecutor.v1.0.exe" />
<TestSummaryBKPSettings>
<Settings MonthDataDuration="" />
<Settings OldDataDuration="" />
<Settings DataTransferLogsPath="Output\Log\DataTransferLogs" SourcePath="E:\User\Test Result"
ThreeMonthDataPath="E:\User\Three_Month_Test_Result_Data"
Old_DataPath="E:\User\Old_Test_Result_Data" />
</TestSummaryBKPSettings>
</BasicSettings>
✅ Explanation
- Created a DTO Class (
TestSettingsDTO
)- This class holds all values, including empty attributes.
- Used
XDocument
to Generate XML<BasicSettings>
root element<TestExecutor>
as an element with an attribute<TestSummaryBKPSettings>
containing multiple<Settings>
elements
- Saved the XML to a File
- Modify
filePath
to set your preferred save location.
- Modify
This will create a structured XML file with the required attributes! If you like comment and share. 🚀
0 Comments