Question

Formatting XML CDATA paragraphs via XSLT

Asked by: Ken_Lyon

Hi everyone,

I've been using a bug tracking system (FogBugz) that allows me to output release notes as HTML or XML. I had used HTML up to now, but I decided it'd be better to use XML and have all the formatting in one place with XSLT. I have found one slight discrepancy, though.

I can get my output to look identical to the HTML equivalent with one difference - all the paragraphs in the same CDATA tag get rendered as a single paragraph. In the HTML version of the document, they had <br/> tags in the appropriate places.

I have tried using <pre></pre> in the XSLT and while that gives me the line breaks I want, I then lose the wrapping of the text.

Is there an easy way to fix this?

Worst case scenario, I'll move the XSLT construction to the ASP.NET page on the server side.

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-08-19 at 02:42:03ID24664148
Tags

C# XML XSLT

Topics

XSL Formatting Objects

,

Programming for ASP.NET

Participating Experts
1
Points
300
Comments
21

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. XSLT removes CDATA Tags
    Hi I have an output file of XML which looks like <CR><CR_NAME><![CDATA["INT-Afghanistan"]]></CR_NAME><CR_SRC><![CDATA[" 98289383"]]></CR_SRC><CR_SRCLEN><![CDATA[" "]]></CR_SRCLEN><C...
  2. ASP.NET Script to Convert XML using XSLT
    I need to know how to convert an XML file into another XML file using an XSLT script. Assume the following: original.xml - the XML to be converted transform.xslt - the XSLT to use to convert original.xml I do not need to serialize the new XML document. Can ASP.NET even seri...
  3. Using xml + xslt to output some asp.net code...doesn…
    Using xml + xslt to output some asp.net code...doesn't work. This is the scenario. I have a set of code files that only vary in 2 places. The rest of the code is the same. I got tired of going through 12-20 all these code files and updating each one when I made an improve...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: abelPosted on 2009-08-19 at 03:32:33ID: 25131126

Not sure I fully understand. Do you mean that the CDATA sections contain HTML layout code? Not sure if this'll help, but if you need to unescape you can use the infamous disable-output-escaping on the xsl:value-of instruction:

<xsl:value-of select="xpath/to/cdata-element" disable-output-escaping="true" />

but if I'm on the wrong track, can you post a bit of your XML and how you want it to look after the XSLT transform?

-- Abel --

 

by: Ken_LyonPosted on 2009-08-19 at 03:38:40ID: 25131169

You're right - it wasn't very clear. I've attached an example.

There are no HTML tags in the CDATA. It is simply a few paragraphs of text, separated by line breaks (don't know if they're CRLF or whatever) in the XML.

The website the data was stored on could export to HTML and it formatted the text by basically replacing every newline with a br tag. That way although it was rendered in a paragraph, you still got the breaks where I wanted them.

<?xml version="1.0" encoding="UTF-8"?>
<ReleaseNotes>
  <sReleaseTitle><![CDATA[Some Text]]></sReleaseTitle>
  <bug>
    <ixBug>123</ixBug>
    <sCategory><![CDATA[Feature]]></sCategory>
    <sTitle><![CDATA[More Text Here]></sTitle>
    <sReleaseNotes><![CDATA[This is the long text.
 
This is the first paragraph of the long text.
 
This is another one. There is no HTML in here, but when the same release notes are generated as HTML, the output has a paragraph section containg a number of br tags at the relevant points.
 
As you can see, the XML simply has some CDATA which preserves the line breaks.]]>
    </sReleaseNotes>
  </bug>
</ReleaseNotes>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:

Select allOpen in new window

 

by: abelPosted on 2009-08-19 at 03:44:36ID: 25131207

> don't know if they're CRLF or whatever

don't worry about that: linebreaks are normalized when XML is parsed. That's mandatory and one of the benefits of using a standard. They're all &#xA; internally.

If you use XSLT 1.0 and not XSLT 2.0 (you can do so by using Saxon for .NET if you wish: www.saxonica.com, the free version), then text processing is a tricky and hard task (I know, you assumed this would be easy, right?). You need to parse it recursively in your XSLT. If you'd use XSLT 2.0 however, a simple tokenizing and a for-each loop would do.

 

by: Ken_LyonPosted on 2009-08-19 at 03:48:07ID: 25131225

When I first wrote the question, I was using an asp:xml control in an ASP.NET page. This wasn't ideal, though, as it didn't give me any control over the header of the page, so I'm now doing it differently.

I'm using .NET's XslCompiledTransform which combines the xslt file and the xml file into the HTML output. I don't know enough about it to know how to make it do custom things. A quick glance at the docs shows that it implements the XSLT 1.0 syntax, though.

private void LoadXml(string filePath) {
    XPathDocument myXPathDoc = new XPathDocument(filePath);
    XslCompiledTransform myXslTrans = new XslCompiledTransform();
    myXslTrans.Load(Server.MapPath(".\\ReleaseNotes.xslt"));
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    myXslTrans.Transform(myXPathDoc, null, sw);
    sw.Close();
    sw.Dispose();
 
    Response.Clear();
    Response.ContentType = "text/xml";
    Response.Write(sb.ToString());
    Response.End();
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: abelPosted on 2009-08-19 at 03:58:23ID: 25131273

Yes, you are correct, XslCompiledTransform implements XSLT 1.0 only. However, using XSLT 1.0 with C# has a different advantage: you can use extension functions to help you with this kind of parsing.

We'll (you'll) have to decide how to tackle this beast: either we stick to XSLT 1.0 with ext functions or in pure XSLT 1.0, or we use Saxon .NET and use XSLT 2.0 syntax.

 

by: Ken_LyonPosted on 2009-08-19 at 03:59:42ID: 25131281

I'd rather just go for the quickest fix for now. If that means writing an extra method in .NET to add br tags, I'd be happy with that.

How do you add an extension function?

 

by: abelPosted on 2009-08-19 at 04:33:46ID: 25131439

You can add an extension function(s) as follows:

  1. Create a public class that can be instantiated from your code above 
  2. Add any method you like, for instance convertNewlineToBr(string s) 
  3. Set debugging to true: new XslCompiledTransform(true) 
  4. In the XsltArgumentList, call AddExtensionObject and add your class (new YourClass()) and give it a namespace. This namespace must exist in the stylesheet. 
  5. In the XsltSettings, set both to true 
  6. In the XSLT file, call your method by its method name, prefixed with the namespace extension 

That's about it. It seems like quite some work, but once you've set it up, it works like a charm. Step 3 (debugging) is only needed during testing of course.

-- Abel --

 

by: abelPosted on 2009-08-19 at 04:38:04ID: 25131464

Alternatively, and perhaps quite a bit easier, I found this possibility in one of my past projects. You still need to enable scripting, but you do not need to register your extension external from your stylesheet:

<!--
add these namespaces to your xsl:stylesheet root element:
xmlns:msxml ="urn:schemas-microsoft-com:xslt"
xmlns:convert = "http://example.com/convert-functions"
-->
 
<msxml:script implements-prefix="convert" language="C#">
  //<![CDATA[
  
    public string NewlineToBr(string s) {
      // write your C# logic here
    }
  
  //]]>
</msxml:script>
 
<!-- 
   call it like this:
-->
 
<xsl:value-of select="convert:NewlineToBr(xpathexpressionhere)" disable-output-escaping="true" />
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

Select allOpen in new window

 

by: Ken_LyonPosted on 2009-08-19 at 05:10:03ID: 25131659

Thanks for these suggestions. I think this is along the right lines. I still need some more help to actually get something that works, though.

Option 1:

* I don't know where these properties reside that you mention in steps 4 and 5.

Option 2:

* I don't actually have an xsl:stylesheet root element. The xslt file starts with an xml declaration and then an opening html tag. I can play about with it, though. I see the default from Visual Studio so I'll copy that.

* Does it matter what i put in the xmlns:convert value? Does it need to point to the actual class that contains the function?

 

by: abelPosted on 2009-08-19 at 05:20:38ID: 25131746

>  I don't actually have an xsl:stylesheet root element.

I mean the file that you refer to here, in this line:

myXslTrans.Load(Server.MapPath(".\\ReleaseNotes.xslt"));

which must be an XSLT file and must start with xsl:stylesheet or it is not an XSLT stylesheet...

> Does it matter what i put in the xmlns:convert value? Does it need to point to the actual class that contains the function?

that's about option "2", where you use the inline possibility with msxml scripting. You can point it to anything, it is a namespace as any other, but one you define. It does not need to exist (as no namespace needs to exist, it is just a unique name, that's all). It cannot, however, have the same value of one of the other namespaces, and it must be a valid URI (but again: does not or should not exist).

Let's focus on option 2 for now, as that is easier.

// xslt settings:
XsltSettings xsltSettings = new XsltSettings(true, true);
 
// xslt arguments (if you want to do option 1 some day)
XsltArgumentList xsltArgs = new XsltArgumentList();
xsltArgs.AddExtensionObject("http://blabla.com", new YourClassHere());
 
// enabling debugging
XslCompiledTransform xslt = new XslCompiledTransform(true);
 
// use the xslt settings:
xslt.Load("yourxsltfilehere.xslt", xsltSettings, null);
 
// use the xslt arguments with the (option 1!) ext methods
xslt.Transform("input.xml", xsltArgs, File.Open("output.xml", FileMode.Create));

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: abelPosted on 2009-08-19 at 05:21:55ID: 25131753

PS: not to be nitpicking, but isn't this quite beyond "easy" by now (hint: points)? Don't worry, I'll help you all the same ;-)

 

by: Ken_LyonPosted on 2009-08-19 at 05:24:55ID: 25131779

I was going to up the points actually, but certainly happy to do so.

I realise that my original xslt file was not really well formed at all, but it worked in a weird sort of way.

I'm now getting this error:

Execution of scripts was prohibited. Use the XsltSettings.EnableScript property to enable it.

The only place I see that property is in XsltSettings.Default.EnableScript. Is this something I should set in the actual xslt file?

 

by: abelPosted on 2009-08-19 at 05:27:26ID: 25131800

> Execution of scripts was prohibited. Use the XsltSettings.EnableScript property to enable it.

well, I believe I was quicker then you: see my penultimate comment about XSLT Settings.

But you're getting close!

 

by: abelPosted on 2009-08-19 at 05:29:16ID: 25131811

>  Is this something I should set in the actual xslt file?

no. It is a security thing. The XSLT files are texts and are used in other ways then through C# code as you do. To prevent illegal scripts (which can open up holes or do things on your system) this is disabled by default. Long story short: you should set it through code as explained above.

 

by: Ken_LyonPosted on 2009-08-19 at 05:32:39ID: 25131840

Sweet! I have success!

I really knew absolutely nothing about XSLT 24 hours ago when I started looking at using it, so it's no surprise I was all over the place there.

It's funny to think that I had to do all that simply to be able to run this line of code:

return s.Replace("\n", "<br />");

Thanks for your help!

 

by: Ken_LyonPosted on 2009-08-19 at 05:38:19ID: 31617501

Very helpful, and nice quick responses.

 

by: abelPosted on 2009-08-19 at 05:48:21ID: 25131968

Yes, indeed. Things that are easy in one language aren't always so easy in others. As a matter of fact, this string manipulation thing is one of the most criticized "features" of XSLT 1.0 and was greatly addressed in XSLT 2.0, including string replace and regular expressions support, as well as tokenizing etc.

Thanks for upping the points, glad I could help!

-- Abel --

 

by: Ken_LyonPosted on 2009-08-19 at 05:53:30ID: 25132006

So is .NET likely to support that any time soon, do you reckon?

 

by: abelPosted on 2009-08-19 at 06:47:04ID: 25132522

.NET supports anything written in .NET. It is a component based system. You can use Saxon.NET for XSLT 2.0, which is a port of the Java version of Saxon. It is extremely standard compliant (has scripting extensions though, which is allowed by the standard anyway) and is written by the creator (chief editor) of the standard.

And who knows, Microsoft said they would do it, but so far, they haven't come with anything but promises (and no timeline).

-- Abel --

 

by: Ken_LyonPosted on 2009-08-19 at 06:48:58ID: 25132543

That's interesting. I would maybe look into Saxon if I was going to be spending more time with XSLT, but I think this is going to be a quick and dirty one-off so I'll just stick with what the Framework has to offer for now.

Thanks again for your help.

 

by: abelPosted on 2009-08-19 at 06:52:36ID: 25132581

FYI: in general, XSLT 2.0 is much easier to work with and XPath 2.0 is much more concise in many respects. Also, the language supports functions and multiple output / input documents and non-XML documents for parsing. If you someday get serious about XSLT, you'd get addicted when working with 2.0 because of its ease and versatility, but with 1.0, you may leave it because of its seeming complexity.

In other words: 2.0 was not "just an upgrade", it was a complete overhaul (though still largely 1.0 compatible).

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...