Reading attribute values with XmlReader
Get a Single, Named Attribute
Use XmlTextReader.GetAttribute (MSDN)
case XmlNodeType.Element: Console.WriteLine(textReader.Name); Console.WriteLine(textReader.Value); Console.WriteLine(textReader.GetAttribute("currency"));
One nice feature of this function: it will not cause an Exception if the attribute is not defined - it will simply return Null
.
Get All the Attributes
Use XmlTextReader.MoveToAttribute (MSDN)
Use the AttributeCount property in combination with MoveToAttribute:
case XmlNodeType.Element: Console.WriteLine(textReader.Name); Console.WriteLine(textReader.Value); for (int attInd = 0; attInd < textReader.AttributeCount; attInd++){ textReader.MoveToAttribute( attInd ); Console.WriteLine(textReader.Name); Console.WriteLine(textReader.Value); } textReader.MoveToElement();
You could change the loop condition a bit so that it also iterates through attributes:
while (textReader.MoveToNextAttribute() || textReader.Read()){ switch (textReader.NodeType) { case XmlNodeType.Element: Console.WriteLine(textReader.Name); Console.WriteLine(textReader.Value); break; //... case XmlNodeType.Attribute: //use textReader.Name and textReader.Value here for attribute name and value break; }}
MoveToNextAttribute
method advances reader to the next attribute in current element or returns false if it cannot do so.