I have this query:
SELECT [content_id]
,[content_html]
,[date_created]
,folder_id
FROM content ct
where folder_id=126
order by content_title
FOR XML PATH('PressRelease'), ROOT ('PressReleases')
When I run this query this is the XML file that is generated:
<PressReleases>
<PressRelease>
<content_id>6442452927</content_id>
<content_html><root><Date>2015-12-02</Date>
<Description><p class="customHeader">jobs to Philadelphia.</p>
<p>mtext in here.</p>
<p>mtext in here.</p>
</Description>
<SEO><h1>Pennsylvania Location</h1>
<div class="bulletRightBar"> The move was made possible in part by the Philadelphia Jobs
Credit</div>
</SEO>
</root></content_html>
<date_created>2015-12-02T09:47:12</date_created>
<folder_id>126</folder_id>
</PressRelease>
<PressReleases>
What I need is this XML file:
<PressReleases>
<PressRelease>
<content_id>6442452927</content_id>
<content_html><root><Date>2015-12-02</Date>
<Description><p class="customHeader">jobs to Philadelphia.</p>
<p>mtext in here.</p>
<p>mtext in here.</p>
</Description>
<SEO><h1>Pennsylvania Location</h1>
<div class="bulletRightBar"> The move was made possible in part by the Philadelphia Jobs
Credit</div>
</SEO>
</root></content_html>
<date_created>2015-12-02T09:47:12</date_created>
<folder_id>126</folder_id>
</PressRelease>
<PressReleases>
Inside the <content_html>
I want to make <root>
<date>
and <Description>
as XML elements but leave the rest as encoded html.
Here's a screenshot for the sql result
It's not pretty, but you could cast the XML field as a string, use the REPLACE function and cast it back to XML like below. You might want to create a function that does this as the line would get with a lot of replacing:
SELECT [content_id]
,cast(REPLACE(cast([content_html] as varchar(max)),'<root>','<root>') as xml)
,[date_created]
,folder_id
FROM content ct
where folder_id=126
order by content_title
FOR XML PATH('PressRelease'), ROOT ('PressReleases')
or here is a way to call it with a function
CREATE FUNCTION [dbo].[XML_Replace]
(@XML_Field XML)
RETURNS XML
BEGIN
DECLARE @xml varchar(max)
DECLARE @xml_Mid varchar(max)
DECLARE @strtBigInt bigint
, @endBigInt bigint
SET @xml = cast(@XML_Field as varchar(max))
SET @strtBigInt = CHARINDEX('<Description>',@xml)
SET @endBigInt = CHARINDEX('</SEO>',@xml)
SET @xml_Mid = SUBSTRING(@xml, @strtBigInt+19,@endBigInt-@strtBigInt-19);
RETURN(cast(REPLACE(REPLACE(REPLACE(REPLACE(substring(@xml,0,@strtBigInt+19),'<','<'),'>','>') + @xml_Mid + REPLACE(REPLACE(substring(@xml,@endBigInt,Len(@xml)),'<','<'),'>','>'),'</Description>','</Description>'),'<SEO>','<SEO>') as xml));
END
Then use the funtion in your code:
SELECT [content_id]
,dbo.XML_Replace([content_html]) as content_html
,[date_created]
,folder_id
FROM content ct
where folder_id=126
order by content_title
FOR XML PATH('PressRelease'), ROOT ('PressReleases')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With