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
"Christoph Schittko [MVP]" <ch********************@austin.rr.com> wrote in
message news:ev**************@TK2MSFTNGP12.phx.gbl...
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.
--
HTH
Christoph Schittko [MVP]
Software Architect, .NET Mentor
"CGuy" <cg**@csharp.net> wrote in message
news:eK**************@tk2msftngp13.phx.gbl... Hi Christoph,
Thanks for your comments. But this doesn't solve my problem - it may
happen that the XML file I'm processing may exist in the harddrive, but
with no data (0 bytes - due to some error in the previous run). So, when I do
while( ( true == xmlReader.Read() ) && ( XmlNodeType.Element !=
xmlReader.NodeType ) ), C# compiler throws an XmlException - "root
element not present". How do I do this without getting this exception?
CGuy
"Christoph Schittko [MVP]" <ch********************@austin.rr.com> wrote
in message news:uF**************@TK2MSFTNGP10.phx.gbl... 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
}
--
HTH
Christoph Schittko [MVP]
Software Architect, .NET Mentor
"CGuy" <cg**@csharp.net> wrote in message
news:uq**************@tk2msftngp13.phx.gbl...
> 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
>
>