解析以下XML在Sql Server中得到错误

时间:2018-09-12 10:42:29

标签: sql-server xml

XML看起来像这样:

DECLARE @xml xml = '<saw:choose xmlns:saw="aaa">
<saw:when condition="true">
<saw:deliveryContent format="excel2007" disposition="attachment">
<saw:headline>
<saw:caption>
<saw:text>Test Mail from bjri-obi-004</saw:text>
</saw:caption>
</saw:headline>
<saw:reportRef path="/shared/BJs Analytics/Agent/Reports/Dana DO & RVP"/>
-<saw:attachmentMessage>
-<saw:caption>
<saw:text>DO & RVP Report</saw:text>
</saw:caption>
</saw:attachmentMessage>
</saw:deliveryContent>
<saw:postActions/>
</saw:when>
-<saw:otherwise>
<saw:postActions/>
</saw:otherwise>
</saw:choose>';

WITH XMLNAMESPACES ('aaa' as saw)
SELECT
 @xml.value('(saw:choose/saw:when/saw:headline/saw:caption/saw:text)[1]','nvarchar(max)')as Textname  

遇到错误

Msg 9421, Level 16, State 1, Line 1
XML parsing: line 9, character 69, illegal name character

当我将&替换为&amp;时,它将返回null的值。

我的结果表应包含

text="Test Mail from bjri-obi-004"
path="/shared/BJs Analytics/Agent/Reports/Dana DO & RVP"
text="DO & RVP Report"

1 个答案:

答案 0 :(得分:0)

需要一些修复。所有&字符都应编码为&amp;。另外,您的路径无效:`saw:deliveryContent丢失。请参见下面的固定示例。

DECLARE @xml xml = '<?xml version="1.0" encoding="UTF-8"?>
<saw:choose xmlns:saw="aaa">
<saw:when condition="true">
<saw:deliveryContent format="excel2007" disposition="attachment">
<saw:headline>
<saw:caption>
<saw:text>Test Mail from bjri-obi-004</saw:text>
</saw:caption>
</saw:headline>
<saw:reportRef path="/shared/BJs Analytics/Agent/Reports/Dana DO &amp; RVP"/>
-<saw:attachmentMessage>
-<saw:caption>
<saw:text>DO &amp; RVP Report</saw:text>
</saw:caption>
</saw:attachmentMessage>
</saw:deliveryContent>
<saw:postActions/>
</saw:when>
-<saw:otherwise>
<saw:postActions/>
</saw:otherwise>
</saw:choose>';

WITH XMLNAMESPACES ('aaa' as saw)
SELECT
 @xml.value('(saw:choose/saw:when/saw:deliveryContent/saw:headline/saw:caption/saw:text)[1]','nvarchar(max)') as Textname