您好我很擅长将T-SQL查询转换为XML。我编写了以下示例查询以获取XML输出,但我的要求需要进行文本调用" Header /"在Message Root之后的第二行。我的问题是“#34; Header"”这个词之间的空白。和" /"。
DECLARE @xmlCar xml;
DECLARE @strCar varchar(max);
DECLARE @sxml xml;
SET @xmlCar = (
SELECT 1 AS [@ID]
,(SELECT 123 AS [AddressID]
,555 AS [AddressNumber]
,'Somewhere Street' AS [AddressStreet]
,'Nashville' AS [AddressCity]
,'TN' AS [AddressState]
,37115 AS [AddressZip]
,'D2QZ0OLXKG' AS [status_rtk/@ID]
,'Institution Tax Status rtk1' AS [status_rtk]
,'D2QZ0OO0BF' AS [category_rtk/@ID]
,'Inst Facility type rtk1' AS [category_rtk]
FOR XML PATH('AddressDemographic'),ROOT('AddressDemographics'),TYPE)
FOR XML PATH('USER'), ROOT('Message'), TYPE)
SET @sxml = REPLACE(CAST(@xmlCar AS VARCHAR(MAX)),'<Message>','<Message><Header/>')
SELECT @sxml
<Message>
<Header />
<USER ID="1">
<AddressDemographics>
<AddressDemographic>
<AddressID>123</AddressID>
<AddressNumber>555</AddressNumber>
<AddressStreet>Somewhere Street</AddressStreet>
<AddressCity>Nashville</AddressCity>
<AddressState>TN</AddressState>
<AddressZip>37115</AddressZip>
<status_rtk ID="D2QZ0OLXKG">Institution Tax Status rtk1</status_rtk>
<category_rtk ID="D2QZ0OO0BF">Inst Facility type rtk1</category_rtk>
</AddressDemographic>
</AddressDemographics>
</USER>
</Message>
答案 0 :(得分:0)
您的查询可能会略有改善,但这不是您问题的答案:
DECLARE @xmlCar xml=
(
SELECT
'' AS [Header]
,(
SELECT 1 AS [@ID]
,123 AS [AddressDemographic/AddressDemographics/AddressID]
,555 AS [AddressDemographic/AddressDemographics/AddressNumber]
,'Somewhere Street' AS [AddressDemographic/AddressDemographics/AddressStreet]
,'Nashville' AS [AddressDemographic/AddressDemographics/AddressCity]
,'TN' AS [AddressDemographic/AddressDemographics/AddressState]
,37115 AS [AddressDemographic/AddressDemographics/AddressZip]
,'D2QZ0OLXKG' AS [AddressDemographic/AddressDemographics/status_rtk/@ID]
,'Institution Tax Status rtk1' AS [AddressDemographic/AddressDemographics/status_rtk]
,'D2QZ0OO0BF' AS [AddressDemographic/AddressDemographics/category_rtk/@ID]
,'Inst Facility type rtk1' AS [AddressDemographic/AddressDemographics/category_rtk]
FOR XML PATH('USER'), TYPE
)
FOR XML PATH('Message')
);
SELECT @xmlCar
你真正问的是这个
我的问题是“标题”和“/”之间的空格
在您自己的尝试中,您使用字符串方法将<Header/>
引入XML。当你看到它的时候,有一片空白来自无处,这令你感到不安......
答案是:这根本没有意义
我不知道,为什么这个空白在你的情况下很重要,但它不应该......
XML不是作为文本存储在内部,而是作为一种树存储。你看到的,只是这个的转录,让你可以阅读。
看看这个例子
SELECT CAST('<root><test><![CDATA[Content with forbidden characters <<>> &]]></test></root>' AS XML)
这被隐含地翻译为
<root>
<test>Some Content with forbidden characters <<>> &</test>
</root>
你明白我的意思吗? XML不只是带有额外字符的文字......
所以答案是:
您的<Header />
元素在语义上与<Header/>
相同。如何显示给用户不是您的主意。
强制执行此的唯一方法是在字符串级别,但我不建议这样做。在这种情况下,只需使用我的查询并添加
SELECT REPLACE(CAST(@xmlCar AS nvarchar(MAX)),'<Header />','<Header/>')