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

时间:2010-08-01 01:25:52

标签: asp.net serialization xml-serialization rijndaelmanaged

我有一个序列化对象,需要作为加密的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字符串,以测试正确的加密字符串是否被发送到另一台机器上的decrypt方法。

我已经在这上面打了一个星期,并且在SO上寻找其他答案,例如: How to return XML in ASP.NET?

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

[UPDATE] 以下是我正在尝试呈现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 个答案:

答案 0 :(得分:1)

您很可能需要在Response对象上设置ContentType。这对应于MIME类型。对于xml,它应该是text/xml

答案 1 :(得分:0)

HtmlEncoding XML字符串也将解决问题。

Response.Write(HttpUtility.HtmlEncode(stringData));