Search code examples
c#xmlxmlreader

How can i read in an element name from an XML document using a reader?


For a college project i am reading an XML document using an XML reader. I have this code so far for reading in XML elements and getting their attribute values, but i also want to verify that the elements i am reading the attribute values from all have a similar name. For example, if the element name is not 'pos' then i dont want to read the attribute from it. Heres my code:

 while(_reader.Read())
 {
   if (_reader.NodeType == XmlNodeType.Element)
   {
     if(_reader.HasAttributes)
     {
       piecesOnBoard[indx] = _reader.GetAttribute("piece");
     }
   }
  indx++;
 }

Solution

  • Just check the Name property of XmlReader

    if(_reader.Name.Equals("pos"))
        DoSomething();
    

    With your code:

    while(_reader.Read())
     {
       if (_reader.NodeType == XmlNodeType.Element)
       {
         if(_reader.HasAttributes && _reader.Name.Equals("pos"))
         {
           piecesOnBoard[indx] = _reader.GetAttribute("piece");
         }
       }
      indx++;
     }