3

How do you convert XmlReader to XmlTextReader?

Code Snippet:

XmlTextReader reader = XmlTextReader.Create(pomfile.FullName);

Here's the Build error I got:

Cannot implicitly convert type 'System.Xml.XmlReader' to 'System.Xml.XmlTextReader'. An

explicit conversion exists(are you missing a cast?).

pomfile is of type FileInfo

skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Take extra care, when calling XmlTextReader.Create you're in fact calling the base static method XmlReader.Create. Always use the base class when calling static method to avoid confusion about the meaning (here, the returned XmlReader will not always be of type XmlTextReader returned). – Julien Lebosquain Oct 08 '09 at 08:54

3 Answers3

2

XmlTextReader.Create() function produces XMLReader that you have to cast to XmlTextReader but this can produce runtime exception if the cast is impossible:

XmlTextReader tr = (XmlTextReader)XmlTextReader.Create(pomfile.FullName));

or you can do this:

XmlTextReader reader = new XmlTextReader(XmlTextReader.Create(pomfile.FullName));

but the best thing to do is:

XmlTextReader reader = new XmlTextReader(pomfile.FullName);
manji
  • 47,442
  • 5
  • 96
  • 103
1

XmlTextReader is obsolete in .NET 2.0. Just do this instead:

XmlReader reader = XmlReader.Create(pomfile.FullName);
Christian Hayter
  • 30,581
  • 6
  • 72
  • 99
  • According to MSDN - "In the Microsoft .NET Framework version 2.0 release, the recommended practice is to create XmlReader instances using the System.Xml.XmlReader.Create method. This allows you to take full advantage of the new features introduced in this release." http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader(v=vs.80).aspx This advice however does not seem to apply for newer framework versions - http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader(v=vs.110).aspx – mvark Dec 27 '13 at 06:51
0

XmlReader is the abstract base class of XmlTextReader so you would need to force a downcast (which I would not advise).

Instantiate the class you are expecting directly (as pointed out in najmeddine's answer)

Community
  • 1
  • 1
The Chairman
  • 7,087
  • 2
  • 36
  • 44