有时webapi在序列化xml时,可能需要给某些带有html或特殊字符(如 < > & /)的字段加上<![CDATA[]]> 已防止影响xml正常数据,如果使用.aspx视图那可直接在前台绑定字段时直接加入<![CDATA[]]>,webapi只有后台代码,那只能在后台做了,如下。

 using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization; namespace MvcApplication1.Controllers
{
public class TestController : ApiController
{
[HttpGet]
[HttpPost]
public HttpResponseMessage HouseTest(string city)
{
//手动构造数据,这里应该是调用构造数据。
var info = new GetHouseCountInfo()
{
CityName = "北京",
CountInfo = new List<CountInfo>()
{
new CountInfo()
{
Data = "2016-08-30",
HouseDetail = "描述信息1111等。。。"
},
new CountInfo()
{
Data = "2016-08-30",
HouseDetail = "描述信息2222等。。。"
},
new CountInfo()
{
Data = "2016-08-30",
HouseDetail = "描述信息333等。。。"
}
}
};
//序列化实体与赋值
var model = new HouseCountRoot {GetHouseInfo = new GetHouseCountInfo()};
model.GetHouseInfo.CountInfo = info.CountInfo;
model.Result = "";
model.Message = "";
model.GetHouseInfo.CityName = info.CityName; return new HttpResponseMessage()
{
Content =
new ObjectContent<HouseCountRoot>(model, new CustomNamespaceXmlFormatter() {UseXmlSerializer = true},
new System.Net.Http.Headers.MediaTypeHeaderValue("application/xml") {CharSet = "utf-8"}),
StatusCode = HttpStatusCode.OK
};
}
} [XmlRoot("houses")]
public class HouseCountRoot
{
[XmlElement("result")]
public string Result { get; set; } [XmlElement("message")]
public string Message { get; set; } [XmlElement("housecount")]
public GetHouseCountInfo GetHouseInfo { get; set; }
} public class GetHouseCountInfo
{
/// <summary>
/// 城市名称
/// </summary>
[XmlElement("cityname")]
public string CityName { get; set; } /// <summary>
/// 房源数信息
/// </summary>
[XmlElement("countinfo")]
public List<CountInfo> CountInfo { get; set; }
} public class CountInfo
{
/// <summary>
/// 日期
/// </summary>
[XmlElement("data")]
public string Data { get; set; } /// <summary>
/// 加<![CDATA[ ]]>数据字段
/// </summary>
[XmlIgnore] //方式1,这里属性设置忽略,把CDataContent设置为housedetail
public string HouseDetail { get; set; } [XmlElement("housedetail")]
public XmlNode[] CDataContent
{
get
{
return new XmlNode[]
{
new XmlDocument().CreateCDataSection(HouseDetail)
};
}
set
{
HouseDetail =
value[].Value;
}
} //方式二,这里把CDataContent设置为housedetail
//[XmlElement("housedetail")]
//public XmlNode CDataContent
//{
// get
// {
// // 这种方式这里代码比上面的要多运行一定次数。
// XmlNode node = new XmlDocument().CreateNode(XmlNodeType.CDATA, "", "");
// node.InnerText = HouseDetail;
// return node;
// }
// set
// {
// HouseDetail
// = value.Value;
// } //省略则CDataContent不会被序列化
//} //以下属性省略。。。。
} /// <summary>
/// 去除xml命名空间的 序列化类
/// </summary>
public class CustomNamespaceXmlFormatter : XmlMediaTypeFormatter
{
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content,
TransportContext transportContext)
{
var xns = new XmlSerializerNamespaces();
foreach (var attribute in type.GetCustomAttributes(true))
{
var xmlRootAttribute = attribute as XmlRootAttribute;
if (xmlRootAttribute != null)
{
xns.Add(string.Empty, xmlRootAttribute.Namespace);
}
} if (xns.Count == )
{
xns.Add(string.Empty, string.Empty);
} var task = Task.Factory.StartNew(() =>
{
var serializer = new XmlSerializer(type);
serializer.Serialize(writeStream, value, xns);
}); return task;
}
}
}

结果如下。

 <?xml version="1.0"?>
<houses>
<result />
<message />
<housecount>
<cityname>北京</cityname>
<countinfo>
<data>2016-08-30</data>
<housedetail><![CDATA[描述信息1111等。。。]]></housedetail>
</countinfo>
<countinfo>
<data>2016-08-30</data>
<housedetail><![CDATA[描述信息2222等。。。]]></housedetail>
</countinfo>
<countinfo>
<data>2016-08-30</data>
<housedetail><![CDATA[描述信息333等。。。]]></housedetail>
</countinfo>
</housecount>
</houses>

asp.net webapi 序列化为xml 时实体属性增加<![CDATA[]]>防止特殊字符的更多相关文章

  1. @JsonInclude(Include.NON_NULL) resttemplate 传递实体参数时 序列化为json时 空字符串不参与序列化

    @JsonInclude(Include.NON_NULL) resttemplate 传递实体参数时 序列化为json时 空字符串不参与序列化 https://www.cnblogs.com/sup ...

  2. 匿名对象序列化为XML

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.X ...

  3. java 使用xom对象数据序列化为xml、反序列化、Preferences相关操作小案例

    package org.rui.io.xml; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import ...

  4. 序列化为XML

    java类序列化成xml 方法[转] 今天看了下JAVA序列化.还是一知半解.怎么也没有弄明白,怎么序列化成XML文件.处入半解状态.在网上找了很多,大部分是理论上的.没有实际的例子.功夫不负有心人, ...

  5. C#实体类序列化为XML

    这两天,应要求做一个C/S的小程序,考虑到程序简洁小巧,存数据的方式不使用数据库,而是直接存入XML文档中保存.为了把复杂实体类里面的属性存入XML,我们可以使用C#有的反射机制,做一个简单的通用工具 ...

  6. 【C#】使用C#将类序列化为XML

    直接上代码: public static class XmlSerializer { public static void SaveToXml(string filePath, object sour ...

  7. 将long数字序列化为json时,转换为字符串

    由于javascript中所有数字都是64位的浮点数,所以整数只能精确的表示53bit长的数字. 在从server得到的json数据中,有ID是长整数类型,在客户端根据此ID生成的link也是不准确的 ...

  8. 如何由XSD自动生成XML和实体类

    项目中有时候要用XML作为数据源,因此需要定义XML文件和相应的类,最佳方法是首先定义XSD,然后自动生成实体类,最后生成XML和填充数据:读取XML数据源的时候,首先用XSD验证XML数据格式,然后 ...

  9. .NET中XML序列化和反序列化常用类和用来控制XML序列化的属性总结(XmlSerializer,XmlTypeAttribute,XmlElementAttribute,XmlAttributeAttribute,XmlArrayAttribute...)

    序列化和反序列化是指什么? 序列化(seriallization): 将对象转化为便于传输的数据格式, 常见的序列化格式:二进制格式,字节数组,json字符串,xml字符串.反序列化(deserial ...

随机推荐

  1. [我给Unity官方视频教程做中文字幕]beginner Graphics – Lessons系列之摄像机介绍Cameras

    [我给Unity官方视频教程做中文字幕]beginner Graphics – Lessons系列之摄像机介绍Cameras 最近得到一些Unity官方视频教程,一看全是纯英文的讲解,没有任何字幕或者 ...

  2. xml存储bug

    最近遇到了一个bug,详细情况如下:用linq to xml写xml文件,在加载的时候代码为xDocument.Load(filePath),保存的时候为xDocument.Save(filePath ...

  3. Redis和Memcached的区别详解

    转载于:http://www.itxuexiwang.com/a/shujukujishu/redis/2016/0216/119.html?1455855360 Redis的作者Salvatore ...

  4. Linux设置SFTP服务用户目录权限

    我们有时会遇到这样的需求,限制一个Linux用户,让他只能在指定的目录下进行添加.修改.删除操作,并且只能使用sftp登录服务器,不能用ssh操作.这些可以通过配置sftp服务实现. 提供sftp服务 ...

  5. KnockoutJS 3.X API 第一章 简介

    本文纯正翻译自官网API文档.其中包含一下个人理解. 官网API地址:http://knockoutjs.com/documentation/introduction.html 简介 Knockout ...

  6. input---checked小问题

    想必有很多做前端同学都遇到了这么一个问题. 那就是checkbox.那就是我们通过jquery设置选中的时候,发现checked属性已经设置上去了 但是选中的样式却没有. 我们做一个简单的测试:看下面 ...

  7. NGUI 可裁剪的灰度Shader

    Shader "Custom/Unlit - Transparent Colored Grayed (SoftClip)" { Properties { _MainTex (&qu ...

  8. 移动web开发之屏幕三要素

    × 目录 [1]屏幕尺寸 [2]分辨率 [3]像素密度 前面的话 实际上,并没有人提过屏幕三要素这个词,仅是我关于移动web开发屏幕相关部分总结归纳的术语.屏幕三要素包括屏幕尺寸.屏幕分辨率和屏幕像素 ...

  9. 开发高效的Tag标签系统数据库设计

    需求背景 目前主流的博客系统.CMS都会有一个TAG标签系统,不仅可以让内容链接的结构化增强,而且可以让文章根据Tag来区分.相比传统老式的Keyword模式,这种Tag模式可以单独的设计一个Map的 ...

  10. c#方法重载,可选参数,命名参数。

    其实这里没什么可说哦,c++的语法大同小异.先看一段代码. class Program { public static void Test(int a) { Console.WriteLine(&qu ...