Brent Scott

Brent Scott

  • NA
  • 1
  • 0

How to check if XML Attribute exists

Aug 24 2006 1:26 PM
I have the following code and I need to check if attributes exist for certain elements.

For example below there is TestAttribute 1 and 2. Sometimes there may be a 3rd one has well...how would I test for that?

FileInfo theFile = new FileInfo("blah.xml");
if (theFile.Exists){
 XmlTextReader myXMLReader = new XmlTextReader("blah.xml");
 while (myXMLReader.Read()){
  if (myXMLReader.NodeType == XmlNodeType.Element && myXMLReader.Name == "TestElement"){
   Console.Write("In Date: " + myXMLReader.GetAttribute("TestAttribute1").ToString() + " ");
   Console.WriteLine("Out Date: " + myXMLReader.GetAttribute("TestAttribute2").ToString() + " ");
  }
 }
}

Many thanks!!

-Brent