在C#中,如何对XML进行编码,以便在页面的JavaScript部分将其输出到JSON中

In C# how to encode XML to output it inside JSON in the JavaScript part of a page

本文关键字:JavaScript JSON 输出 XML 编码      更新时间:2023-09-26

我有一个处理程序,它上传一个KML文件并返回带有KML文件作为属性的JSON:

context.Response.Write("{'"name'":'"" + FileName + 
"'",'"type'":'"" + FileType + 
"'",'"size'":'"" + FileSize + 
"'",'"region_id'":'"" + regionID + 
"'",'"kml'":'"" + HttpUtility.HtmlEncode(xmlData) + "'"}");

正如你所看到的,我正试图用HttpUtility.HtmlEncode对KML进行编码,但我的响应中出现了一个错误:

未捕获的异常:无效的JSON

如何在C#中对XML/KML文件进行属性编码,以便以后在JavaScript中对其进行解码

编辑#1:根据Cheeso的评论我使用的是ASP.NET,IIS 7.5 Windows 7上的.NET版本4。我的处理程序是一个ashx文件。如果我在响应中省略了KML数据(HttpUtility.HtmlEncode(xmlData)),则响应工作正常。

编辑#2我还试着根据主持人的评论使用System.Web.Script.Serialization.JavaScriptSerializer。我是这样用的:

System.Web.Script.Serialization.JavaScriptSerializer serializer;
context.Response.Write("{'"name'":'"" + FileName + 
"'",'"type'":'"" + FileType + 
"'",'"size'":'"" + FileSize + 
"'",'"region_id'":'"" + regionID + 
"'",'"kml'":'"" + serializer.Serialize(xmlData) + "'"}");

我仍然得到相同的"无效JSON"错误。

您想要构建JSON,对吧。。。显然,我建议使用JSON序列化程序是荒谬的。。。。然而:

string FileName = "foo.txt", FileType = "csv";
int FileSize = 1134, regionID = 12;
string xml = "<foo><bar/></foo>";
string json= new JavaScriptSerializer().Serialize(new {
    name = FileName,
    type = FileType,
    size = FileSize,
    region_id = regionID,
    kml = xml
});

在大多数情况下,使用预封装的序列化程序既更方便,又对数据的边缘情况更健壮。

HTML编码器将<编码为&lt;,依此类推。这并不能帮助您将XML转换为JSON格式。你想要的是一个JavaScript编码。使用HttpUtility.JavaScriptStringEncode

http://msdn.microsoft.com/en-us/library/dd991914.aspx