How to read and write data in XML using C# by node name

How to Read and Write data in XML using c#. How to read data from CMD in C# and write the data in an XML file.

In this example, we will see an easy and simple process to read and write data in an XML file using C#. Let’s focus on the below steps.

Read and write data in XML using C#

Create an XML file and save it(Remember the file location).

<?xml version="1.0" standalone="yes"?>
<URL>Enter Your Text Here</URL>

Write a C# program to write the data in XML file

//Find the location of xml file
string filepath = @"C:\Users\cis\Desktop\folder\Demo.xml";
// Create an object of DataSet()
DataSet ds = new DataSet();
//Read the XML file from the saved location
//Read the node name of XML where we need to enter the data
ds.Tables[0].Rows[0]["URL"] = "Enter the data here";
//Finally Write the data in the XML file

Write a C# program to read data from CMD.

string value1 = args[0];
string value2 = args[1];
Console.WriteLine(value1+ " : "+value2);

In the above code, we have two string value1 and value2 that will pass while running the program from CMD. So open CMD and file the location of the .exe file of your c# program and run the .exe file with two-parameter. In my case, the program name is “swap.exe” and the location in D drive.

Command to run the swap.exe with two parameters

D:\New folder (2)\swap\bin\Debug>swap.exe Hello Hello_C#
Hello: Hello_C#

Write a C# program to read data from CMD and write in XML.

using System.Linq;

namespace WriteDataInXML
class WriteDataInXML
static void Main(string[] args)

string filepath = @"C:\Users\bhupi\Desktop\folder\new.xml";
DataSet ds = new DataSet();
if (args.Count() > 0)
ds.Tables[0].Rows[0]["URL"] = args[0];
ds.Tables[0].Rows[0]["Kiosk"] = args[1];

In the above code, we are going to read data from CMD and write the same data In the new.xml file. Now let’s see how to read data from an XML file using Node name.

Read data from an XML file using C#.

public static string GetValueFromXML(string TagName)
string path1 = AppDomain.CurrentDomain.BaseDirectory.Replace("\\bin\\Debug", "");
string path = path1 + "new.xml";
string text = System.IO.File.ReadAllText(path);
XmlDocument xmlDoc = new XmlDocument();
XmlNodeList xnList = xmlDoc.SelectNodes("/Datas/Data");
string URLdata = null;
foreach (XmlNode xn in xnList)
URLdata = xn[TagName].InnerText;
return URLdata;

GetValueFromXML is a custom method that will return data of an XML node in a string format and take input as tag name while calling this method.

Example to call this method
string data = GetValueFromXML(“URL”);

How to run Jenkin’s job using dynamic base URL