Convert Strings to XML Attributes in C#
In this article, we will explore how to accomplish this transformation using C#. Below is a C# program that takes a string input and converts it into XML attributes:
using System;
using System.Xml;
class Program
{
static void Main(string[] args)
{
// Input string
string input = "name=\"Raj\" age=\"30\" city=\"Mumbai\"";
// Create XML element
XmlDocument doc = new XmlDocument();
XmlElement element = doc.CreateElement("Person");
// Split the input string by spaces
string[] attributes = input.Split(' ');
// Add attributes to the XML element
foreach (string attribute in attributes)
{
string[] parts = attribute.Split('=');
string attributeName = parts[0];
string attributeValue = parts[1].Trim('"');
element.SetAttribute(attributeName, attributeValue);
}
// Display the XML element
Console.WriteLine(element.OuterXml);
}
}
Output:
<Person name="Raj" age="30" city="Mumbai" />
Comments (0)