0

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;
      }
   }
}
Alberto
  • 15,626
  • 9
  • 43
  • 56

4 Answers4

1

Why not create a dataset according to your xml scheme? Then you get all stuff as gift automatically. I would prefer this. Helps much and is reusable later on for any other stuff.

icbytes
  • 1,831
  • 1
  • 17
  • 27
1

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

string piece = _reader.GetAttribute("piece");
har07
  • 88,338
  • 12
  • 84
  • 137
1

Yo, here's the Microsoft tutorial hope it helps. MSDN

1

I made one of these a while, back when i begun programming. This may not be the most efficient way but it will work.

XmlReader ReadXML = XmlReader.Create("XML FILE"); //Creates XMLReader instance

   while (ReadXML.NodeType != XmlNodeType.EndElement) //Sets the node types to closes. 
    {
       ReadXML.Read(); //Reads the XML Doc
            if (ReadXML.Name == "Child") //Focuses node 
            {
               while (ReadXML.NodeType != XmlNodeType.EndElement)//If the node is not empty
                 {
                    ReadXML.Read();
                    if (ReadXML.NodeType == XmlNodeType.Text) //Gets the text in the node
                    {
                        Console.WriteLine("In 'Child' node = {0}", ReadXML.Value);
                        Console.ReadKey();
                    }
                }
          }
      }
rguarascia.ts
  • 694
  • 7
  • 19