24

I have an XML file that I'm trying to read from here, and have the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;

namespace XML
{
    class Program
    {
        static void Main(string[] args)
        {
            XmlTextReader textReader = new XmlTextReader("secLendingXML.cfm.xml");
            while (textReader.Read())
            {
                switch (textReader.NodeType)
                {
                    case XmlNodeType.Element:
                        Console.WriteLine(textReader.Name);
                        Console.WriteLine(textReader.Value);
                        break;
                    case XmlNodeType.Text:
                        Console.WriteLine(textReader.Value);
                        break;
                    case XmlNodeType.XmlDeclaration:
                    case XmlNodeType.ProcessingInstruction:
                        Console.WriteLine(textReader.Name + " " + textReader.Value);
                        break;
                    case XmlNodeType.Comment:
                        Console.WriteLine(textReader.Value);
                        break;
                    case XmlNodeType.EndElement:
                        break;
                }
            }
            Console.ReadLine();
        }
    }
}

The code is working properly in the sense that it's reading the nodes and returning the names. But, the issue is that I'm trying to also retrieve the data within the nodes. In other words, when it reads the first section after the test section, it will read:

slnc:DataSet
slnc:Group
slnc:Section
slnc:ActualAvailableToBorrow
*** here ***
slnc:oustandingLoans

This is where I want the textreader to read the following values within the node like confidentiality="F", currency="USD", etc., but it just skips right to the next section without reading these values!

<slnc:actualAvailableToBorrow xmlns:slnc="http://www.newyorkfed.org/xml/schemas/SecLending" 
      confidentiality="F" currency="USD" decimals="0" method="AA" 
      multiplier="5" securityLendingType="AA" status="A" value="1474"/>

How do I get the textreader to read the attribute values? It would be ideal for it to print the value "currency", and then its value: "F", and so on.

Chuck Savage
  • 11,775
  • 6
  • 49
  • 69
weskpga
  • 2,017
  • 7
  • 29
  • 43

2 Answers2

57

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(); 
JDB
  • 25,172
  • 5
  • 72
  • 123
  • 1
    Thanks, this is exactly what I'm looking for. Just a quick follow up question - do you know if there's a function that will get every attribute in a node, or do I have to do that manually? – weskpga Jun 19 '12 at 17:41
  • I think [ghord's answer](http://stackoverflow.com/a/31098559/211627) might be slightly more performant, since you don't have to rewind the text reader after reading the attributes. But I've not tested so I don't know how big a difference it makes (probably not much). I recommend that you choose the option that makes your code easy to read, then refactor if testing shows a significant performance bottleneck. – JDB Mar 06 '17 at 15:38
21

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.

ghord
  • 13,260
  • 6
  • 44
  • 69
  • 1
    This is a nice idea, I was trying to test this with no results, but didn't notice the crucial addition in the `while` statement `textReader.MoveToNextAttribute()` ! – wired00 Nov 01 '15 at 04:26