Convert XML Attributes to Strings in C#
XML (eXtensible Markup Language) is a popular format for storing and transporting data, commonly used in various applications. In this article, we will explore how to achieve this task easily.
Let's start by considering a sample XML document:
<book title="Principles of Information Systems" author="George Reynolds" year="2020" />
Our goal is to extract the attributes (title
, author
, and year
) and convert their values to strings using C#.
We can use the XDocument
class from the System.Xml.Linq
namespace, which provides a convenient API for parsing and querying XML data in C#. Here's how we can do it:
using System;
using System.Xml.Linq;
class Program
{
static void Main(string[] args)
{
// Define the XML string
string xmlString = "<book title=\"Principles of Information Systems\" author=\"George Reynolds\" year=\"2020\" />";
// Parse the XML string into an XDocument
XDocument doc = XDocument.Parse(xmlString);
// Extract and convert attributes to strings
string title = doc.Root.Attribute("title").Value;
string author = doc.Root.Attribute("author").Value;
string year = doc.Root.Attribute("year").Value;
// Output the results
Console.WriteLine($"Title: {title}");
Console.WriteLine($"Author: {author}");
Console.WriteLine($"Year: {year}");
}
}
We defined the XML string containing our sample data. We then used XDocument.Parse
to parse the XML string into an XDocument
object. Next, we extracted the attribute values using the Attribute
method and convert them to strings using the Value
property.
Output:
Title: Principles of Information Systems
Author: George Reynolds
Year: 2020
Comments (0)