XmlReader Question

  • Thread starter Thread starter CGuy
  • Start date Start date
C

CGuy

Hi,

I am using an XmlTextReader to read an xml file. It may happen that the
file is present in the disk, but it may be empty (0 bytes). I would like to
find out whether the xml file contains a valid root node or not. How do I do
this?

This is what I need
if(File.Exists(fileName))
{
XmlTextReader xmReader = new XmlTextReader(fileName);
//How do I find out whether this xml document contains a Root node named
"ROOT_NODE" or not?
}

CGuy
 
You can loop with the reader through the document until you find the first
element node and then check if node's name is not ROOT_NODE. The code goes
something like this:

while( ( true == xmlReader.Read() )
&& ( XmlNodeType.Element != xmlReader.NodeType ) ) {}

// now we're at the first element node and can check the name:
if( "ROOT_NODE" == xmlReader.Name )
{
// it is ...
}
else
{
// it isn't
}
 
I don't know about any way to avoid the exception, but could you help me
understand what's bad about the exception? Does the exception not contain
enough information for you? Is "no root element" the same state as "empty
file" or do you need to treat them separately? You can easily do both by
handling the exception correctly, but I'd like to understand before I post
more samples.
 
Hi Christoph,

I wanted to avoid the exception because I wanted to avoid nested
try-catch blocks (In the code, I have 2 outer levels tray-catch blocks).
Anyway, I have followed your approach and everything works fine. This is how
I have done it

try
{
//Initialize XmlTextWriter
try
{
XmlTextReader xmReader = new XmlTextReader(stream);
while(xmReader.Read() == true)
{
if(xmReader.NodeType == XmlNodeType.Element && xmReader.Name ==
"ROOT_NODES")
{
//Has root node
break;
}
}
}
catch(XmlException)
{
xmWriter.WriteStartDocument();
xmWriter.WriteStartElement("ROOT_NODE");
}
}
finally
{
//Writer the Header for current session
}
}
catch()
{
...
}


Thanks again
CGuy
 
Back
Top