Search code examples
c#xmlxmlreader

How can i read in attributes from an XML document in C#?


For a college project i was recently assigned i need to create an XML document that will represent a chessboard. So i created elements for each space on the chessboard and then i want to assign an attribute to each space element that contains the name of the piece that is there. For example:

<pos piece="R"/>

would be a Rook.

When it comes to the C# program, how can i read in the attribute value i am using a loop like so:

while(_reader.Read())
{
   if (_reader.NodeType == XmlNodeType.Element)
   {
      if(_reader.HasAttributes)
      {
           //This is where i want to assign the attribute to a char
           char piece;
      }
   }
}

Solution

  • You can use XmlReader.GetAttribute() method to get XML attribute value :

    string piece = _reader.GetAttribute("piece");