Retrieves the value of a specified attribute.
name
: string
{http://www.w3.org/2000/xmlns/}xmlns
).
string
null
if the attribute is not found.
This method allows you to easily access attribute values for the current node. If the attribute does not exist, null
is returned, preventing potential exceptions.
using System;
using System.Xml;
public class Example
{
public static void Main(string[] args)
{
string xmlString = "<root><element attribute1=\"value1\" attribute2=\"value2\" /></root>";
XmlReader reader = new XmlNodeReader(XmlDocument.Create(xmlString).DocumentElement);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "element")
{
string attr1Value = reader.GetAttribute("attribute1");
string attr2Value = reader.GetAttribute("attribute2");
string nonExistentAttr = reader.GetAttribute("nonExistent");
Console.WriteLine($"Attribute1: {attr1Value}"); // Output: Attribute1: value1
Console.WriteLine($"Attribute2: {attr2Value}"); // Output: Attribute2: value2
Console.WriteLine($"NonExistent: {nonExistentAttr ?? "null"}"); // Output: NonExistent: null
}
}
reader.Close();
}
}