Проблема с правильной вложенностью с использованием SQL Server FOR XML EXPLICIT - PullRequest
0 голосов
/ 09 июля 2009

Я пытаюсь создать XML-файл базы данных рецептов, в котором рецепты содержат ингредиенты в качестве подэлементов. Мой запрос такой:

select 
    1 as 'Tag'
,null as 'parent'
,replace(r.recipe_name, '/', '') as 'item!1!title!element'
,isnull(replace(r.description, '/', ''), '') as 'item!1!description!cdata'
,r.recipe_id as 'item!1!recipe_id!element'
,null as 'ingredients!2!ingredient!element'
from recipe r
union all
select
    2 as 'Tag'
    ,1 as 'parent'
    ,null as 'item!1!title!element'
    ,null as 'item!1!description!cdata'
    ,r.recipe_id as 'item!1!recipe_id!element'
    ,i.full_ingredient_txt as 'ingredients!2!ingredient!element'
from
    recipe r, ingredient i
    where r.recipe_id = i.recipe_id
order by 'item!1!recipe_id!element'
for xml explicit

, который генерирует следующий XML:

<item>
  <title>3-D Cookie Packages</title>
  <description><![CDATA[]]></description>
  <recipe_id>52576</recipe_id>
  <ingredients>
    <ingredient>Assorted candy decorations, if desired</ingredient>
  </ingredients>
  <ingredients>
    <ingredient>cup butter or margarine, softened</ingredient>
  </ingredients>
  <ingredients>
    <ingredient>cup sugar</ingredient>
  </ingredients>
</item>

Что я действительно хочу, так это чтобы мои ингредиенты гнездились так:

    <ingredients>
        <ingredient>Assorted candy decorations, if desired</ingredient>
        <ingredient>cup butter or margarine, softened</ingredient>
        <ingredient>cup sugar</ingredient>
    </ingredients>

Я не могу использовать FOR XML PATH, потому что мне нужно объявление CDATA в поле описания, которое не поддерживается с помощью этого метода.

1 Ответ

1 голос
/ 09 июля 2009

Это должно сделать это. Добавлен дополнительный уровень для хранения узла родительских ингредиентов

select 
1 as Tag
,null as Parent
,replace(r.recipe_name, '/', '') as 'item!1!title!element'
,isnull(replace(r.description, '/', ''), '') as 'item!1!description!cdata'
,r.recipe_id as 'item!1!recipe_id!element'
,null as 'ingredients!2!'
,null as 'ingredient!3!'
from recipe r
union all
  select
    2 as Tag
    ,1 as Parent
    ,null
    ,null
    ,r.recipe_id
    ,''
    ,null
from recipe r
union all
  select
    3 as Tag
    ,2 as Parent
    ,null
    ,null
    ,r.recipe_id
    ,null
    ,i.full_ingredient_txt
from  
    recipe r, ingredient i
    where r.recipe_id = i.recipe_id
order by 'item!1!recipe_id!element'
for xml explicit
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...