XmlReader Question

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
 
C

Christoph Schittko [MVP]

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
}
 
C

Christoph Schittko [MVP]

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.
 
C

CGuy

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top