MSDN .NET Documentation

MoveToAttribute Method

Moves the reader to the specified attribute.

Declaration

public bool MoveToAttribute(
    string name
)

Parameters

  • name: The name of the attribute to move to.

Return Value

true if the attribute is found; otherwise, false.

Remarks

If the current node is an element node, MoveToAttribute attempts to move the reader to the attribute with the specified name. If the attribute is found, the reader's NodeType property is set to XmlNodeType.Attribute, and the reader is positioned on the attribute. If the attribute is not found, the reader remains on the element node.

This method is useful when you want to access specific attributes of an element directly without iterating through all attributes using GetAttribute or MoveToNextAttribute.

Examples

C# Example

using System;
using System.Xml;

public class Example
{
    public static void Main()
    {
        string xml = @"<root><item id='1' name='ExampleItem' /></root>";
        using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
        {
            reader.ReadToDescendant("item");

            if (reader.MoveToAttribute("id"))
            {
                Console.WriteLine("Attribute 'id' found: " + reader.Value);
            }

            if (reader.MoveToAttribute("name"))
            {
                Console.WriteLine("Attribute 'name' found: " + reader.Value);
            }

            // Move back to the element node
            reader.MoveToElement();
            Console.WriteLine("Current node type: " + reader.NodeType);
        }
    }
}

See Also