在SQL中使用CAST中的和号 [英] Use ampersand in CAST in SQL

查看:152
本文介绍了在SQL中使用CAST中的和号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQL Server 2005上的以下代码段在&符号上失败:

  select cast('< name> Spolsky& atwood< / name>'as xml)

/ p>

更长的解释,我需要更新XML列中的一些数据,我使用搜索&通过将XML值转换为varchar来替换类型hack,执行替换并使用此转换更新XML列。

解决方案

  select cast('< name> Spolsky& amp; Atwood< / name>'as xml)

XML XML 标准不允许使用标记,并且此类文档将无法通过任何 XML 解析器。



XMLSerializer()将输出&符号 HTML -encoded。



以下代码:

  .Xml.Serialization; 

命名空间xml
{
public class MyData
{
public string name =Spolsky& Atwood;
}

类程序
{
static void Main(string [] args)
{
new XmlSerializer .Serialize(System.Console.Out,new MyData());
}
}
}

将输出以下内容: / p>

 <?xml version =1.0encoding =utf-8?& 
< MyData
xmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd =http://www.w3.org / 2001 / XMLSchema>
< name> Spolsky& amp; Atwood< / name>
< / MyData>

,而改为使用& amp; &


The following code snippet on SQL server 2005 fails on the ampersand '&':

select cast('<name>Spolsky & Atwood</name>' as xml)

Does anyone know a workaround?

Longer explanation, I need to update some data in an XML column, and I'm using a search & replace type hack by casting the XML value to a varchar, doing the replace and updating the XML column with this cast.

解决方案

select cast('<name>Spolsky &amp; Atwood</name>' as xml)

A literal ampersand inside an XML tag is not allowed by the XML standard, and such a document will fail to parse by any XML parser.

An XMLSerializer() will output the ampersand HTML-encoded.

The following code:

using System.Xml.Serialization;

namespace xml
{
    public class MyData
    {
        public string name = "Spolsky & Atwood";
    }

    class Program
    {
        static void Main(string[] args)
        {
            new XmlSerializer(typeof(MyData)).Serialize(System.Console.Out, new MyData());
        }
    }
}

will output the following:

<?xml version="1.0" encoding="utf-8"?>
<MyData
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <name>Spolsky &amp; Atwood</name>
</MyData>

, with an &amp; instead of &.

这篇关于在SQL中使用CAST中的和号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆