【发布时间】:2020-11-11 20:33:49
【问题描述】:
这个问题是 XML 文件中有 xhtml 标记(请参阅 Example_Code 元素),当我运行 XQuery 时,它似乎去除了标记并只保留了文本。我想将 Example_Code 的值完全存储在 XML 文件中的表中。 非常感谢您的阅读。
DECLARE @Xml XML =
N'
<Demonstrative_Examples xmlns:xhtml="http://www.w3.org/1999/xhtml">>
<Demonstrative_Example>
<Intro_Text>This is the intro</Intro_Text>
<Example_Code Nature="bad">Example 1.1</Example_Code>
<Body_Text>Body 1.1</Body_Text>
<Example_Code> <xhtml:div>String sessionID = generateSessionId();<xhtml:br/>Cookie c = new Cookie("session_id", sessionID);<xhtml:br/>response.addCookie(c);</xhtml:div>
</Example_Code>
</Demonstrative_Example>
<Demonstrative_Example>
<Intro_Text>This is the 2nd intro</Intro_Text>
<Body_Text>Body 2.1</Body_Text>
<Example_Code Nature="Good">Example 2.1</Example_Code>
</Demonstrative_Example>
</Demonstrative_Examples>';
-- just to see
;WITH XMLNAMESPACES ('http://www.w3.org/1999/xhtml' as xhtml)
SELECT @xml.query('<root>
{
for $x in /Demonstrative_Examples/Demonstrative_Example
let $id := count(/Demonstrative_Examples/Demonstrative_Example[. << $x[1]]) + 1
for $y in $x/*[position() gt 1]
let $pos := count($x/*[. << $y[1]]) + 1
let $it := $x/*[local-name()="Intro_Text"]
return <r id="{$id}" pos="{$pos - 1}"
Intro_Text="{$it}"
Body_Text="{$y[local-name()="Body_Text"]/text()}"
Example_Code="{$y[local-name()="Example_Code"]}"
Nature="{$y[local-name()="Example_Code"]/@Nature}"></r>
}
</root>') AS xmldata;
-- real deal
;WITH rs AS
(
SELECT @xml.query('<root>
{
for $x in /Demonstrative_Examples/Demonstrative_Example
let $id := count(/Demonstrative_Examples/Demonstrative_Example[. << $x[1]]) + 1
for $y in $x/*[position() gt 1]
let $pos := count($x/*[. << $y[1]]) + 1
let $it := $x/*[local-name()="Intro_Text"]
return <r id="{$id}" pos="{$pos - 1}"
Intro_Text="{$it}"
Body_Text="{$y[local-name()="Body_Text"]/text()}"
Example_Code="{$y[local-name()="Example_Code"]/text()}"
Nature="{$y[local-name()="Example_Code"]/@Nature}"></r>
}
</root>') AS xmldata
)
SELECT c.value('@id', 'INT') AS [ID]
, c.value('@pos', 'INT') AS [Order]
, c.value('@Intro_Text', 'VARCHAR(30)') AS [Intro_Text]
, c.value('@Body_Text', 'VARCHAR(30)') AS [Body_Text]
, c.value('@Example_Code', 'VARCHAR(30)') AS [Example_Code]
, c.value('@Nature', 'VARCHAR(30)') AS [Nature]
FROM rs CROSS APPLY xmldata.nodes('/root/r') AS t(c);
这是结果集:
【问题讨论】:
标签: sql-server xml