?
Solved

Generate an xml file with StringWriter(UTF-8) ??

Posted on 2003-03-18
3
Medium Priority
?
16,605 Views
Last Modified: 2008-02-01
When I try to generate an xml file with StringWriter,   I can’t change the encoding (UTF-16) to UTF-8. This application, having to have a format xml(utf-8) To preserve compatibility with other programs.

Ex
StringWriter s = new StringWriter();                  
XmlTextWriter tw = new XmlTextWriter(s,Encoding.UTF-8);            

Don’t work, I am receive a error message “C:\Inetpub\wwwroot\LicenceTools\site\GenerateXmlTreeView.aspx.cs(58): Argument '1': cannot convert from 'System.IO.StringWriter' to 'System.IO.Stream'”



I would like having <?xml version="1.0" encoding="utf-8"?>  rather than <?xml version="1.0" encoding="utf-16"?>

Could you help me?


Thanks in advance

PS: It s a stream for WebServer.

Application Code:
Htm:
<%@ Page language="c#" Codebehind="GenerateXmlTreeView.aspx.cs" AutoEventWireup="false" Inherits="LicenceTools.site.GenerateXmlTreeView"  %>

C#:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using ZZDataFromDb.ZZConn;
using ZZTools.ZZTools;
using System.Xml;
using System.IO;
using System.Globalization;
using System.Text;
using System.Xml.XPath;

namespace LicenceTools.site
{
      /// <summary>
      /// Summary description for GenerateXmlTreeView.
      /// </summary>
      public class GenerateXmlTreeView : System.Web.UI.Page
      {
            
            private void Page_Load(object sender, System.EventArgs e)
            {                                    
                  //StringReader = new StreamReader("site/GenerateXmlTreeView.aspx");                  
                  string strSelect;
                  // Put user code to initialize the page here
                  if( Request.QueryString["select"] != null)
                  {
                        strSelect =Request.QueryString["select"];
                  }else {
                        strSelect= "";
                  }
                  string strIdCompany;
                  if( Request.QueryString["IdCompany"] != null)
                  {
                        strIdCompany =Request.QueryString["IdCompany"];
                  }
                  else
                  {
                        strIdCompany= "%";
                  }
                  
                  DataContainer dc=new DataContainer();                        // create a data container for this function                  
                  dc.Set("select", strSelect);                  // add the user name                  
                  dc.Set("IdCompany", strIdCompany);                  // add the user name                  
                  DBData dts=new DBData(dc);                                    // create a interface to the DB technology
                  DataTable DT;
                  DT = dts.QueryMultiRow("sql_fillTreeView");                  // query if the account exists.  Always returns a value
                  //Xml Generate
                  ArrayContainer Level = new ArrayContainer(100);
                  StringWriter s = new StringWriter();                  
                  //string test = s.Encoding.ToString();
                  XmlTextWriter tw = new XmlTextWriter(s);// ,Encoding.UTF8                                    

                  tw.Formatting=Formatting.Indented;
                  tw.WriteStartDocument();
                  tw.WriteStartElement("treeview");
                  tw.WriteAttributeString("title","Licenses Tool");                  
                  tw.WriteStartElement("custom-parameters");
                  tw.WriteStartElement("param");
                        tw.WriteAttributeString("name","shift-width");                  
                        tw.WriteAttributeString("value","15");                  
                  tw.WriteEndElement();
                  tw.WriteStartElement("param");
                        tw.WriteAttributeString("name","img-directory");                  
                        tw.WriteAttributeString("img-directory","images/");                  
                  tw.WriteEndElement();



                  tw.WriteEndElement();
                  int level=0;                        
                  string IdElement;
                  Level.add("");
                  string Name;
                  string IdPrduit;
                  string IdParent;
                  string License;
                  string PrevIdParent="";
                  string PrevIdElement="";
                  bool FlagElementFirst= true ;                  
                  foreach(DataRow r in DT.Rows){
                        if (FlagElementFirst == true)
                        {
                              Level.Remove(0);
                              Level.add(r["idParent"].ToString());                              
                        }
                        IdElement =  r["id"].ToString();
                        Name      =       r["Name"].ToString();
                        IdPrduit  =  r["IdPrduit"].ToString();
                        IdParent  =  r["idParent"].ToString();
                        License   =  r["license"].ToString();
                        if((  Level[IdParent]>=level ||level==0 ))
                        {
                              if((IdParent=="" || IdParent!=PrevIdParent ) && (IdPrduit=="") )
                              {                                    
                                    Console.WriteLine("Name");
                                    tw.WriteStartElement("folder");
                                          tw.WriteAttributeString("title",Name);                  
                                          if (FlagElementFirst == true)
                                          {
                                                tw.WriteAttributeString("img","folder");                                                      
                                          }
                                          else
                                          {                                          
                                                tw.WriteAttributeString("img","folder");                                                      
                                          }
                                    level++ ;
                                    Level.add(IdElement);
                                    PrevIdParent=IdParent;
                                    PrevIdElement =IdElement;
                              }
                              else if((IdParent==PrevIdParent)&& IdParent!="" && (IdPrduit=="") )
                              {                                    
                                                          
                              }
                              else if(IdPrduit!="")
                              {
                                    string reg;
                                    if(License=="Y") {reg="true";}
                                    else {reg="false" ; }                                    
                                    tw.WriteStartElement("leaf");
                                          tw.WriteAttributeString("title",Name);      
                                          tw.WriteAttributeString("url", IdElement);      
                                          tw.WriteAttributeString("registered",reg);                                                      
                                    tw.WriteEndElement();
                                    //tw.WriteAttributeString("test","test");
                              }                              
                        }
                        else
                        {
                              while(level>Level[IdParent])
                              {
                                    tw.WriteEndElement();
                                    Level.Remove(level);
                                    level--;
                              }                                                            
                              if(IdPrduit !="")
                              {
                                    //tw.WriteElementString(Name,IdPrduit);
                                    string reg;
                                    if(License=="Y") {reg="true";}
                                    else {reg="false" ; }                                    
                                    tw.WriteStartElement("leaf");
                                          tw.WriteAttributeString("title",Name);      
                                          tw.WriteAttributeString("url",IdElement);      
                                          tw.WriteAttributeString("registered",reg);                                                      
                                    tw.WriteEndElement();

                              }
                              else
                              {
                                    tw.WriteStartElement("folder");
                                          tw.WriteAttributeString("title",Name);                  
                                          tw.WriteAttributeString("img","folder.gif");            
                                    Level.add(IdElement);
                                    PrevIdParent=IdParent;
                                    PrevIdElement =IdElement;                                                             
                                    level++;
                              }
                        }
                        FlagElementFirst = false;
                  }
                  tw.WriteEndDocument();
                  tw.Flush();
                  tw.Close();                  
                  Response.Clear();
                  Response.ContentEncoding = Encoding.UTF8;//
                  //Encoding.GetEncoding(1251) ;
                  Response.ContentType="text/xml";
                  Response.Write(s.ToString());            
            }
            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Load += new System.EventHandler(this.Page_Load);
            }
            #endregion
      }
}
      
0
Comment
Question by:zoltix
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 

Author Comment

by:zoltix
ID: 8158725
public class StringWriterWithEncoding : StringWriter
{
    Encoding encoding;

    public StringWriterWithEncoding (Encoding encoding)
    {
        this.encoding = encoding;
    }

    public override Encoding Encoding
    {
        get { return encoding; }
    }
}

Then you'd do:

XmlTextWriter = new XmlTextWriter
    (new StringWriterWithEncoding (Encoding.UTF8));
0
 

Author Comment

by:zoltix
ID: 8159090
Thanks a lot.  It works..... somebody,  send me an others solution which work too

public class StringWriterWithEncoding : StringWriter
{
   Encoding encoding;

   public StringWriterWithEncoding (Encoding encoding)
   {
       this.encoding = encoding;
   }

   public override Encoding Encoding
   {
       get { return encoding; }
   }
}

Then you'd do:

XmlTextWriter = new XmlTextWriter
   (new StringWriterWithEncoding (Encoding.UTF8));
0
 
LVL 14

Accepted Solution

by:
AvonWyss earned 300 total points
ID: 8167989
You don't need the StringWriter at all.

Just use the following code to create your XmlTextWriter:

XmlTextWriter tw = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

This enables your code to directly write to the response stream without the unneccesary buffering in the StreamWriter. Because of this, the following line is obsolete:

Response.Clear();
and
Response.Write(s.ToString());
at the end of your function.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question