开发者

Casting from System.XmlWriter to System.XmlTextWriter

开发者 https://www.devze.com 2023-02-14 04:25 出处:网络
How can I cast XmlWriter to XmlTextWriter in C开发者_运维问答#? thanksXmlTextWriter subclasses XmlWriter, so, if your XmlWriter is indeed an XmlTextWriter, you can just cast it like anything else. If

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消