在 SQL 中的 CAST 中使用 & 符号
SQL Server 2005 上的以下代码片段在与号“&”上失败:
select cast('<name>Spolsky & Atwood</name>' as xml)
有人知道解决方法吗?
更长的解释,我需要更新 XML 列中的一些数据,并且我正在使用搜索和搜索。 通过将 XML 值强制转换为 varchar 来替换类型 hack,并使用此强制转换执行替换和更新 XML 列。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
XML
标准不允许在XML
标记内使用文字与符号,这样的文档将无法被任何XML
解析器解析。XMLSerializer()
将输出 & 符号HTML
编码。以下代码:
将输出以下内容:
,并使用
&
而不是&
。A literal ampersand inside an
XML
tag is not allowed by theXML
standard, and such a document will fail to parse by anyXML
parser.An
XMLSerializer()
will output the ampersandHTML
-encoded.The following code:
will output the following:
, with an
&
instead of&
.它不是有效的 XML。 使用
&
:It's not valid XML. Use
&
:您还需要对文本进行 XML 转义。
因此,让我们回溯并假设您正在构建该字符串:
您想做的事情更像是:
当然,您可能应该满足其他实体的需求,因此:
You'd need to XML escape the text, too.
So let's backtrack and assume you're building that string as:
you'd want to do something more like:
Of course, you probable should cater for the other entities thus:
在 SQL 中使用 XML 时,使用内置函数比手动转换要安全得多。
以下代码将构建一个正确的 SQL XML 变量,它看起来像基于原始字符串的所需输出:
When working with XML in SQL you're a lot safer using built-in functions instead of converting it manually.
The following code will build a proper SQL XML variable that looks like your desired output based on a raw string:
正如 John 和 Quassnoi 所说,
&
本身是无效的。 这是因为 & 字符是字符实体的开头 - 用于指定无法按字面表示的字符。 实体有两种形式 - 一种通过名称指定字符(例如,&
或"
),另一种通过其名称指定字符代码(我相信它是 Unicode 字符集中的代码位置,但不确定。例如,"
应该代表双引号)。因此,要在 HTML 文档中包含文字
&
,您必须指定它的实体:&
。 您可能遇到的其他常见问题是<
表示<
,>
表示>
,"
表示"
。As John and Quassnoi state,
&
on it's own is not valid. This is because the ampersand character is the start of a character entity - used to specify characters that cannot be represented literally. There are two forms of entity - one specifies the character by name (e.g.,&
, or"
), and one the specifies the character by it's code (I believe it's the code position within the Unicode character set, but not sure. e.g.,"
should represent a double quote).Thus, to include a literal
&
in a HTML document, you must specify it's entity:&
. Other common ones you may encounter are<
for<
,>
for>
, and"
for"
.