This issue is that there is xhtml markup inside the XML file (see Example_Code element) and when I run the XQuery it seems to strip out the markup and retain only the text. I would like to store the value of Example_Code in the table exactly as it is in the XML file . Many thanks for reading.
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);
This is the resultset:
