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>

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Footer Logo

Subscribe

Select Categories