C#创建XML字符串

//webService

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;
using System.Text;
using System.IO;

[WebService(Namespace 
= "webservice")] //(Namespace = "http://localhost/webserver/")
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
    
public Service () {

        
//如果使用设计的组件,请取消注释以下行 
        
//InitializeComponent(); 
    }


    [WebMethod]
    
public string HelloWorld() {
        
return "Hello World";
    }


    [WebMethod] 
    
public  string  show(string  yourname) 
    

        
//return  "http://aaaaa"+"欢迎"+yourname;

       
//生成xml字符串:
        using (StringWriter sw = new StringWriter())
        
{
            XmlTextWriter xtw 
= new XmlTextWriter(sw);
            xtw.Formatting 
= Formatting.Indented;
            xtw.WriteStartDocument();

            xtw.WriteStartElement(
"root");

            
//test
            xtw.WriteStartElement("test");
            xtw.WriteString(
"test content");
            xtw.WriteEndElement();

            
//test2
            xtw.WriteStartElement("test2");

            
//testSub
            xtw.WriteStartElement("testSub");
            xtw.WriteString(
"Sub content");
            xtw.WriteEndElement();

            xtw.WriteEndElement();
        

            xtw.WriteEndElement();
//root
            xtw.WriteEndDocument();            
          
            
string result = sw.ToString();

            
return result.Replace("utf-8""gb2312").Replace("utf-16""gb2312");
        }
 
    }


    
    [WebMethod] 
    
public string parseXML()
    
{
        
////解析xml:
        string strInput = "<?xml version='1.0' encoding='utf-16'?><foo><bar /></foo>";
        XmlTextReader r 
= new XmlTextReader(new StringReader(strInput));
        MemoryStream ms 
= new MemoryStream();
        XmlTextWriter w 
= new XmlTextWriter(ms, Encoding.UTF8);
        w.WriteNode(r, 
false);
        w.Flush();
        ms.Position 
= 0;
        StreamReader sr 
= new StreamReader(ms);
        
string strOutput = sr.ReadToEnd();
        
return strOutput.Replace("utf-8""gb2312").Replace("utf-16""gb2312");
        
//Console.WriteLine("Input = {0}, Output = {1}", strInput.Length, strOutput.Length);
    }
 
    
}

posted @ 2007-06-06 22:04  blueKnight  Views(2675)  Comments(1Edit  收藏  举报