I am looking to create an output xml in this format but I'm not able to add the nodes Features and Categories under Child. I can add one at a time but not both.
<Parent>
<Child>
<Features>
<Feature Id="f1" />
<Feature Id="f2" />
<Feature Id="f3" />
</Features>
<Categories>
<Category Name="c1">
<Feature>f1</Feature>
<Feature>f2</Feature>
</Category>
<Category Name="c2">
<Feature>f2</Feature>
<Feature>f3</Feature>
</Category>
<Category Name="c3">
<Feature>f2</Feature>
</Category>
</Child>
</Parent>
Here's my SQL to create the two XML strings with the <Features> node and <Category> node:
DECLARE @CategoryFeatures TABLE (CategoryId VARCHAR(5), FeatureId VARCHAR(5))
INSERT INTO @CategoryFeatures VALUES ('c1', 'f1')
INSERT INTO @CategoryFeatures VALUES ('c1', 'f2')
INSERT INTO @CategoryFeatures VALUES ('c2', 'f2')
INSERT INTO @CategoryFeatures VALUES ('c2', 'f3')
INSERT INTO @CategoryFeatures VALUES ('c3', 'f2')
SELECT
(
SELECT
(
SELECT [@Id] = FeatureId
FROM CategoryFeatures
GROUP BY FeatureId
FOR XML PATH ('Feature'), ROOT ('Features'), TYPE)
FOR XML PATH ('Child'), TYPE)
FOR XML PATH ('Parent')
SELECT
(
SELECT
(
SELECT [@Name] = cat.CategoryId,
(
SELECT Feature = cf.FeatureId
FROM CategoryFeatures cf
WHERE cf.CategoryId = cat.CategoryId
FOR XML PATH (''), TYPE)
FROM CategoryFeatures cat
GROUP BY cat.CategoryId
FOR XML PATH ('Category'), ROOT ('Categories'), TYPE)
FOR XML PATH ('Child'), TYPE)
FOR XML PATH ('Parent')
How can I get these two nodes at the same level to make it look like the expected output above? Thank you.