简体   繁体   中英

Casting from System.XmlWriter to System.XmlTextWriter

How can I cast XmlWriter to XmlTextWriter in C#?

thanks

XmlTextWriter subclasses XmlWriter, so, if your XmlWriter is indeed an XmlTextWriter, you can just cast it like anything else. If your XmlWriter is any other subclass of XmlWriter, your cast would fail.

You can check the type and then cast

if (xmlWriter is XmlTextWriter)
{
    XmlTextWriter xmlTextWriter = (XmlTextWriter)xmlWriter;
    // add code here
}

Or you can use as to give it a shot and then see if it worked out.

XmlTextWriter xmlTextWriter = xmlWriter as XmlTextWriter;

if (null != xmlTextWriter)
{
    // add code here
}

XmlTextWriter is inheriting from XmlWriter . So unless the XmlWriter you have is an XmlTextWriter , you can't cast it that way. You could do

var textWriter = xmlWriter as XmlTextWriter;
if (textWriter != null)
{
    ...
}

Why not instantiate the XmlTextWriter to begin with?

The same way you would perform any other cast (assuming your instance is actually an XmlTextWriter).

The following case below works:

using System;
using System.Xml;

class Test
{
     static void Main(string[] args)
     {
          XmlWriter xmlWriter = XmlWriter.Create("MyXml.xml");
          XmlTextWriter xmlTextWriter = xmlWriter as XmlTextWriter;
          if(xmlTextWriter != null)
          {
               //perform operations here...
          }
     }   
}

You should note they recommend using XmlWriter.Create to create XmlWriter instances.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM