• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 219
  • Last Modified:

Unable to read xml attribute... why?

I have the following C# code snippet:
------------------------    start    -----------------------
XmlTextReader tr = new XmlTextReader(xmlFilename);
            if (File.Exists(xmlFilename))
            {
                tr.Read();
                tr.MoveToElement();  // Move to first element
                googleFileID = tr.GetAttribute("RegFileID");  //<-------------------------- not working
            }
-----------------------    end of code    ----------------------

and this is the xml file I am trying to read with the above code:

-------------------------     start    --------------------------
<?xml version="1.0"?>
<GoogleSettings UserID="rolfmarsh" RegFileID="abc" BookStoreName="prager" VISA="Y" MasterCard="Y" AMEX="Y" Discover="N" PayPalDoesAll="Y" GoogleCheckout="N" Location="" MediaMail="N" PriorityMail="N" ExpressMail="N" Intl="N" IntlAir="N" UPSGround="N" UPSAir="N" />
--------------------------    end    ----------------------------

Can someone please tell me why the code won't read the attribute?
0
rmmarsh
Asked:
rmmarsh
  • 2
1 Solution
 
JimBrandleyCommented:
To get to the beginning, you need to:
reader.MoveToContent();

Then read the attribute.

0
 
rmmarshAuthor Commented:
You're the man!  Thank you so much!
0
 
icrCommented:
Firstly, I would imagine you would want to move XmlTextReader tr = new XmlTextReader(xmlFilename); to inside the if statement to avoid the overhead of creating the reader if the file doesn't exist. However, I can imagine cases where putting it outside is legitimate, so apologies if yours is one of those cases.

As JimBrandley suggested, you need to use MoveToContent, so the code would look like this:

XmlTextReader tr = new XmlTextReader(xmlFilename);
if (File.Exists(xmlFilename))
{
    tr.MoveToContent();
    googleFileID = tr.GetAttribute("RegFileID");
}
0
 
JimBrandleyCommented:
My pleasure. Good luck!
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now