tags:

views:

201

answers:

2

My application produces an xml file that is then xslt transformed into a nice html report. I have a problem with \n however. There are some xslt techniques to do it, but they are pretty awkward and time consuming.

So my solution was to do a string.replace \n to

< br />

and then to force the xmlWriter to write this with WriteRaw(text). The problem is that the text sometimes has some illegal chars like >.

I am unable to find any utility method in .net that just takes in a string and transforms it in a xml-friendly string. I looked with the reflector and the class that handles this logic is not public.

Any ideeas (beside writing my own code to do this)?

+3  A: 

I think the solution to this question will help you:

xslt replace \n with <br/> only in one node?

You can incorporate the provided template into your transformation process, and you're done without getting your hands dirty.

Tomalak
Thanks, that worked. I was aware of your post but I was searching for a faster solution. I now choose not to optimize early:).
Bogdan Gavril
Hm. That's a good decision, I guess. ;-) If you feel like it, you can post some performance measurements here. My guess is that it's actually not catastrophically slow. And it ensures valid output.
Tomalak
+4  A: 

Never, ever use string manipulation to produce XML. It's not just that it makes poorly-socialized people laugh at you: it leads to code that has bugs in it that you don't know exist.

Think about it from a test-driven perspective. You've written a method that uses string manipulation to generate XML. Okay, now write a test case for it that demonstrates that it will never emit poorly-formed XML. In order for the test to prove this, you have to test every possible scenario outlined in the XML recommendation. Do you know the XML recommendation well enough to be able to assert that your test does this?

No, you don't. And you don't really want to, not unless you're writing a framework for XML generation. That's why you use the classes in System.Xml to generate XML. The people who wrote them did that work so that you don't have to.

Tomalak showed how to do what you're trying to do with XSLT. If you're using an XmlWriter to generate the XML, use this pattern:

string s = "replace\nnewlines\nwith\nbreaks";
string[] lines = s.Split('\n');
for (int i=0; i<lines.Length; i++)
{
    xw.WriteString(lines[i]);
    if (i<lines.Length - 1)
    {
        xw.WriteElementString("br", "", "");
    }
}

This uses string manipulation where it's appropriate - when manipulating string data outside of XML - and doesn't where it's not - when producing XML text.

Robert Rossney
You make a good point, Robert.
Bogdan Gavril