C#
XML
XmlNode
attribute value
programming tutorial

How to read attribute value from XmlNode in C?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Reading an attribute from an XmlNode in C# is straightforward once you know which API surface you are holding. The main points are to select the correct node, read from its Attributes collection safely, and handle missing nodes or namespaces without crashing.

Read From the Attributes Collection

If you already have an XmlNode, the usual approach is to look up the attribute by name and then read its Value.

csharp
1using System;
2using System.Xml;
3
4var xml = @"<book id=""42"" category=""tech"">
5              <title>XML in C#</title>
6            </book>";
7
8var doc = new XmlDocument();
9doc.LoadXml(xml);
10
11XmlNode? node = doc.SelectSingleNode("/book");
12string? id = node?.Attributes?["id"]?.Value;
13string? category = node?.Attributes?["category"]?.Value;
14
15Console.WriteLine(id);        // 42
16Console.WriteLine(category);  // tech

This pattern is safe because each access uses null-aware checks. If the node or attribute does not exist, the result is null instead of an exception.

Use XmlElement When You Can

Many XML nodes are elements, and XmlElement offers a slightly nicer method: GetAttribute. If you know the selected node is an element, you can cast it and use that API directly.

csharp
1using System;
2using System.Xml;
3
4var doc = new XmlDocument();
5doc.LoadXml(@"<user name=""Ada"" role=""admin"" />");
6
7var element = (XmlElement?)doc.SelectSingleNode("/user");
8
9if (element is not null)
10{
11    string name = element.GetAttribute("name");
12    string role = element.GetAttribute("role");
13
14    Console.WriteLine(name); // Ada
15    Console.WriteLine(role); // admin
16}

GetAttribute returns an empty string when the attribute is missing, which can be convenient for quick parsing. If you need to distinguish between "missing" and "present but empty," inspect the attribute node explicitly instead.

Selecting the Right Node Matters

A lot of XML bugs are really node-selection bugs. If SelectSingleNode points at the wrong place, the attribute lookup naturally fails.

For example, this XML stores the attribute on book, not on title:

xml
<book id="42">
  <title>XML in C#</title>
</book>

So this works:

csharp
XmlNode? book = doc.SelectSingleNode("/book");
string? id = book?.Attributes?["id"]?.Value;

But this does not:

csharp
XmlNode? title = doc.SelectSingleNode("/book/title");
string? id = title?.Attributes?["id"]?.Value; // null

Before blaming the attribute lookup, confirm the XPath actually targets the element that owns the attribute.

Handling Namespaces

When XML uses namespaces, plain XPath expressions often stop matching. In that case, create an XmlNamespaceManager, register the namespace prefix, and use that prefix in the query.

csharp
1using System;
2using System.Xml;
3
4var xml = @"<ns:book xmlns:ns=""urn:demo"" id=""42"" />";
5var doc = new XmlDocument();
6doc.LoadXml(xml);
7
8var manager = new XmlNamespaceManager(doc.NameTable);
9manager.AddNamespace("ns", "urn:demo");
10
11XmlNode? node = doc.SelectSingleNode("/ns:book", manager);
12string? id = node?.Attributes?["id"]?.Value;
13
14Console.WriteLine(id); // 42

If you skip the namespace manager, SelectSingleNode may return null even though the XML looks correct.

Returning a Fallback Value

For production code, it is often useful to centralize the logic in a helper method:

csharp
1using System.Xml;
2
3static string? ReadAttribute(XmlNode? node, string attributeName)
4{
5    return node?.Attributes?[attributeName]?.Value;
6}

This keeps parsing code small and makes missing-attribute behavior consistent across the codebase.

Common Pitfalls

The most common mistake is assuming every XmlNode has an Attributes collection. Text nodes, comments, and other node types do not behave like elements, so attribute lookups on them return nothing useful.

Another frequent issue is not checking for null. SelectSingleNode returns null when the XPath misses, and node.Attributes["id"].Value then throws an exception. The null-safe access pattern avoids that.

Namespaces are another source of confusion. If a document declares a namespace, the XPath usually needs a namespace manager, even when the attribute itself is not namespaced.

Summary

  • Use node.Attributes["name"]?.Value when you already have an XmlNode.
  • Use XmlElement.GetAttribute when the node is known to be an element.
  • Verify the XPath selects the element that actually owns the attribute.
  • Add an XmlNamespaceManager when the XML uses namespaces.
  • Handle missing nodes and attributes safely so XML parsing fails gracefully.

Course illustration
Course illustration

All Rights Reserved.