.NET Core

Generate Dynamic XML File In .NET Core

In this article, we are going to create an XML File Dynamically and store it in the folder. we are going to use the System.Xml namespace for creating XML.

we are going to use XmlDocument which Represents XML documents. by using this we can create(add), edit, load, validate XML in a document.

XmlNode is used to define a single node in the XML document.

CreateElement() method will create element specified by Name.

AppendChild() method will Add a specified node at the end of the list of particular specified child nodes.

CreateTextNode() method will create a text node with the specified text.

SetAttribute() method will Set the value of the particular attribute with the specified name.

Below is the method for Creating XML dynamically,

public bool CreateEmployeeXML()
        {
            try
            {
                //XmlDo
                XmlDocument doc = new XmlDocument();
                XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
                doc.AppendChild(docNode);


                XmlElement employeeDataNode = doc.CreateElement("EmployeeData");
                (employeeDataNode).SetAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                (employeeDataNode).SetAttribute("schemaLocation", "http://www.w3.org/2001/XMLSchema-instance", "http://www.testwebsite.org/data/schema/rr/2021 xy-abc-1-1.xsd");
                (employeeDataNode).SetAttribute("xmlns", "http://www.testwebsite.org/data/schema/rr/2021");

                doc.AppendChild(employeeDataNode);

                XmlNode headertNode = doc.CreateElement("Header");
                employeeDataNode.AppendChild(headertNode);


                XmlNode contentDateNode = doc.CreateElement("ContentDate");
                contentDateNode.AppendChild(doc.CreateTextNode("2017-02-01T12:00:00Z"));
                headertNode.AppendChild(contentDateNode);


                //RelationshipRecords
                XmlNode employeeRecordsNode = doc.CreateElement("EmployeeRecords");
                doc.DocumentElement.AppendChild(employeeRecordsNode);

                XmlNode employeeRecordNode = doc.CreateElement("EmployeeRecord");
                employeeRecordsNode.AppendChild(employeeRecordNode);


                //EmployeeName
                XmlNode employeeNameNode = doc.CreateElement("EmployeeName");
                employeeNameNode.AppendChild(doc.CreateTextNode("TABISH RANGREJ"));
                employeeRecordNode.AppendChild(employeeNameNode);

                //EmployeeType
                XmlNode employeeTypeNode = doc.CreateElement("EmployeeType");
                employeeTypeNode.AppendChild(doc.CreateTextNode("USER"));
                employeeRecordNode.AppendChild(employeeTypeNode);

                //StartNode
                XmlNode addressNode = doc.CreateElement("Address");
                employeeRecordNode.AppendChild(addressNode);

                XmlNode addressLineNode = doc.CreateElement("AddressLine");
                addressLineNode.AppendChild(doc.CreateTextNode("1/234 xyz building, xyz park, 395003"));
                addressNode.AppendChild(addressLineNode);

                XmlNode countryNode = doc.CreateElement("Country");
                countryNode.AppendChild(doc.CreateTextNode("UAE"));
                addressNode.AppendChild(countryNode);

                //EmployeeSubscriptions
                XmlNode employeeSubscriptionsNode = doc.CreateElement("EmployeeSubscriptions");
                employeeRecordNode.AppendChild(employeeSubscriptionsNode);

                //EmployeeSubscription
                XmlNode employeeSubscriptionNode = doc.CreateElement("EmployeeSubscription");
                employeeSubscriptionsNode.AppendChild(employeeSubscriptionNode);

                XmlNode startDateNode = doc.CreateElement("StartDate");
                startDateNode.AppendChild(doc.CreateTextNode("2018-02-01T00:00:00Z"));
                employeeSubscriptionNode.AppendChild(startDateNode);

                XmlNode endDateNode = doc.CreateElement("EndDate");
                endDateNode.AppendChild(doc.CreateTextNode("2020-02-01T00:00:00Z"));
                employeeSubscriptionNode.AppendChild(endDateNode);

                XmlNode periodTypeNode = doc.CreateElement("SubscriptionType");
                periodTypeNode.AppendChild(doc.CreateTextNode("VIP"));
                employeeSubscriptionNode.AppendChild(periodTypeNode);


                //RelationshipStatus
                XmlNode employeeStatusNode = doc.CreateElement("EmployeeStatus");

                employeeStatusNode.AppendChild(doc.CreateTextNode("ACTIVE"));
                employeeRecordNode.AppendChild(employeeStatusNode);


                var basePath = Path.Combine(Environment.CurrentDirectory, @"XmlFiles\");
                if (!Directory.Exists(basePath))
                {
                    Directory.CreateDirectory(basePath);
                }
                var newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString("N"), ".xml");
                doc.Save(basePath + newFileName);


                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

the above method will create employee-related XML Dynamically. it will store that XML in the XmlFiles folder by providing a unique FileName that is generated from NewGuid (like- bce95a1969b0468d95f6358888e6f897.xml). in the above code, I passed the value statically, you can pass it from the model or from the database, as per your requirement.

it will create XML as given below,

<?xml version="1.0" encoding="UTF-8"?>
<EmployeeData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.testwebsite.org/data/schema/rr/2021 xy-abc-1-1.xsd" xmlns="http://www.testwebsite.org/data/schema/rr/2021">
  <Header>
    <ContentDate>2017-02-01T12:00:00Z</ContentDate>
  </Header>
  <EmployeeRecords>
    <EmployeeRecord>
      <EmployeeName>TABISH RANGREJ</EmployeeName>
      <EmployeeType>USER</EmployeeType>
      <Address>
        <AddressLine>1/234 xyz building, xyz park, 395003</AddressLine>
        <Country>UAE</Country>
      </Address>
      <EmployeeSubscriptions>
        <EmployeeSubscription>
          <StartDate>2018-02-01T00:00:00Z</StartDate>
          <EndDate>2020-02-01T00:00:00Z</EndDate>
          <SubscriptionType>VIP</SubscriptionType>
        </EmployeeSubscription>
      </EmployeeSubscriptions>
      <EmployeeStatus>ACTIVE</EmployeeStatus>
    </EmployeeRecord>
  </EmployeeRecords>
</EmployeeData>

 

Tabish Rangrej

Tabish Rangrej is an Experienced .NET Team Leader, software engineer, and Author with a demonstrated history of working in the IT industry. He has quite well experience in developing, communicating, managing, and writing in his field. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, ASP.NET CORE, Angular, AngularJS, Web API, SQL, Entity Framework, JavaScript, Jquery, Different Integrations like Quickbooks, Stripe, Google APIs, Zoho, Orion, Xero, etc., Different versioning tools like TFS, SVN, GIT, etc. and Windows services. Strong engineering professional with a Master of Computer Applications - MCA focused on Computer Science from Veer Narmad South Gujarat University, Surat. Tabish is always ready to accept new challenges and learn new things, he would like to serve better for the community.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago