码迷,mamicode.com
首页 > 数据库 > 详细

SQL2008使用json.net实现XML与JSON互转

时间:2015-04-08 14:53:05      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:

借助CLR,首先实现字符串的互转

?

?

public class JsonFunction

{

/// <summary>

/// XMLJSON

/// </summary>

/// <param name="xml"></param>

/// <returns></returns>

/// <remarks>

/// json不建议太长

/// </remarks>

[Microsoft.SqlServer.Server.SqlFunction(Name = "Xml2Json")]

public static SqlString Xml2Json(SqlXml xml)

{

System.Xml.XmlDocument doc=new System.Xml.XmlDocument();

doc.LoadXml(xml.Value);

string json= JsonConvert.SerializeXmlNode(doc, Formatting.Indented);

doc.Clone();

return new SqlString(json);

?

}

[Microsoft.SqlServer.Server.SqlFunction(Name = "Json2Xml")]

public static SqlXml Json2Xml(string json)

{

System.Xml.XmlDocument doc = JsonConvert.DeserializeXmlNode(json);

System.IO.StringWriter sw=new System.IO.StringWriter();

doc.WriteTo(new System.Xml.XmlTextWriter(sw));

return new SqlXml(new System.Xml.XmlTextReader(new System.IO.StringReader( sw.ToString())));

?

}

}

?

测试语句

?

DROP TABLE test

?

CREATE TABLE TEST ( NAME VARCHAR(5), DATA XML )

?

GO

?

?

INSERT INTO TEST

VALUES ( ‘A‘, ‘<ROOT><M>AAAA</M></ROOT>‘ ),

( ‘B‘, ‘<ROOT><D>00000</D></ROOT>‘ )

?

DECLARE @X XML

SELECT @x = ( SELECT *

FROM test

FOR

XML AUTO ,

ELEMENTS ,

ROOT

)

SELECT @x

DECLARE @json NVARCHAR(MAX)

SELECT @json = dbo.xml2json(@x)

SELECT @json

SELECT dbo.Json2Xml(@json)

?

?

SQL2008使用json.net实现XML与JSON互转

标签:

原文地址:http://www.cnblogs.com/QinQouShui/p/4402208.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!