代码之家  ›  专栏  ›  技术社区  ›  IrishChieftain

将序列化XML写入字符串并在浏览器中显示

  •  0
  • IrishChieftain  · 技术社区  · 14 年前

    我有一个序列化对象,它需要作为加密的XML字符串发送。我可以将序列化对象保存到格式良好的XML文件中,但这不是我想要的。我已经让Rijndael加密/解密为一个示例字符串工作。

    Person person = new Person("Irish", "Chieftain");
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
    
    // Write serialized XML to file
    System.Guid guid = System.Guid.NewGuid();
    StreamWriter streamWriter 
        = new StreamWriter(@"C:\application" + "_" + guid.ToString() + ".xml")
    xmlSerializer.Serialize(streamWriter.BaseStream, person);
    

    我希望能够在浏览器中显示XML字符串 在加密之前,测试是否将正确的加密字符串发送到另一台计算机上的解密方法。

    我已经为此打了一个星期,并寻找了其他答案,例如: How to return XML in ASP.NET?

    有人能告诉我在浏览器中将生成的XML显示为字符串的正确语法吗?

    [更新] 下面是我试图呈现XML的内容:

    MemoryStream memoryStream = new MemoryStream();
    XmlTextWriter xmlWriter2 = new XmlTextWriter(memoryStream, Encoding.UTF8); 
    xmlWriter2.Formatting = Formatting.Indented;
    xmlSerializer.Serialize(xmlWriter2, person);
    memoryStream = (MemoryStream) xmlWriter2.BaseStream;
    UTF8Encoding encoding2 = new UTF8Encoding();
    stringData = encoding2.GetString(memoryStream.ToArray());
    Response.ContentType = "text/xml";
    Response.Write(stringData);
    

    [更新2 ]

    如果我删除了“text/xml”内容类型,那么当我查看源代码时会得到以下信息(这是正确的吗?):

    <?xml version="1.0" encoding="utf-8"?>
    <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <FirstName>Irish</FirstName>
      <SecondName>Chieftain</SecondName>
    </Person>
    

    [更新3 ]

    工作版本:

                #region Display original string
                // Write serialized XML to a string - Display purposes.
                MemoryStream memoryStream = new MemoryStream();
                XmlTextWriter xmlWriter2 
                    = new XmlTextWriter(memoryStream, Encoding.UTF8);
                xmlWriter2.Formatting = Formatting.Indented;
                xmlSerializer.Serialize(xmlWriter2, person);
                memoryStream = (MemoryStream) xmlWriter2.BaseStream;
                UTF8Encoding encoding2 = new UTF8Encoding();
                stringData = encoding2.GetString(memoryStream.ToArray());
    
                Response.Clear();
                Response.ContentType = "text/xml";
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                Response.Cache.SetAllowResponseInBrowserHistory(true);
                Response.Write(stringData);
                Response.End();
                #endregion
    
    2 回复  |  直到 12 年前
        1
  •  1
  •   Muad'Dib    14 年前

    很可能您需要设置 ContentType 在您的响应对象上。这对应于mime类型。对于XML,应该是 text/xml

        2
  •  0
  •   mahesh reddy    12 年前

    htmlencoding XML字符串也将解决此问题。

    response.write(httputility.htmlencode(stringdata));