为什么要用流的形式呢?
使用System.Xml.XmlTextWriter
直接写入一个临时的XML文件中不就可以了吗?
然后再用System.Xml.XmlTextReader从中读出来就可以了
//写的例子
System.Xml.XmlTextWriter writer = new XmlTextWriter(filePath,System.Text.Encoding.Default);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("IMClientStart");
writer.WriteAttributeString("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance"); writer.WriteStartElement("Server");
writer.WriteElementString("IP",InitData.ServerIP.ToString());
writer.WriteElementString("Port",InitData.BASE_SERVER_PORT.ToString());
writer.WriteEndElement(); writer.WriteStartElement("UserList");
for( int i=0;i<userList.Count;i++)
{
writer.WriteElementString("UserID",userList[i].ToString());
}
writer.WriteEndElement(); writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();//读的例子
System.Xml.XmlTextReader reader = new XmlTextReader( "文件名.xml");
reader.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
while( reader.Read() )
{
if( reader.NodeType == System.Xml.XmlNodeType.Element )
{
nodeText = reader.Name;
switch( nodeText )
{
case "IP":
ip = reader.ReadString();
break;
case "Port":
port = reader.ReadString();
break;
case "UserID":
Login.UserIDList.Add( reader.ReadString());
break;
}
}
}

解决方案 »

  1.   

    TO hxhbluestar(贺星河) :
    非常感谢你的例子,但我现在的目的是动态的生成一个XML文档,而这个文档并不是从文件里读出来,也不写入文件,只是可能用于某种操作,完了以后是要销毁的。
      

  2.   

    不是很明白你到底要什么,你应该举个例子说明,不过,参考using System;
    using System.Xml;
    using System.Text;
    using System.IO;class TestXmlSt
    {
      static void Main()
      {

    MemoryStream ms = new MemoryStream();
    writeMyDoc(ms);

    string s = System.Text.Encoding.Default.GetString(ms.ToArray());
    Console.WriteLine(s);

      }  static  bool writeMyDoc(System.IO.Stream output)
      {
    XmlDocument doc = new XmlDocument();
    XmlElement e = doc.CreateElement("root");
    doc.AppendChild(e); XmlElement c = doc.CreateElement("child");
    c.InnerText = "hello world";
    e.AppendChild(c); doc.Save(output); return true;
      }
    }