tags:

views:

936

answers:

2

I need to save content that containing newlines in some XML attributes, not text. The method should be picked so that I am able to decode it in XSLT 1.0/ESXLT/XSLT 2.0

What is the best encoding method?

Please suggest/give some ideas.

+3  A: 

You can use the entity 
 to represent a newline in an XML attribute. 
 can be used to represent a carriage return. A windows style CRLF could be represented as 
.

This is legal XML syntax. See XML spec for more details.

Asaph
Is it a valid XML Character??
Chathuranga Chandrasekara
I guess i have to use some encoding instead of entity As getAttribute wont work with a string containing newline. Do you have many idea? Will entity solve the getAttribute problem?
Tommy
@Chathuranga Chandrasekara: Yes. It's valid XML. I updated my answer to include a link to the XML spec where these symbols are mentioned.
Asaph
@Tommy: What programming language/API are you using? What is this `getAttribute()` method you speak of?
Asaph
@Asaph: Javascript. client side: javascript. server side: php (xslt 1.0/esxlt), tomcat (xslt 2.0 saxon8).
Tommy
@Tommy: Are you *sure* `getAttribute` won't decode `` and convert it to a newline? It should work. Did you test it?
Asaph
+9  A: 

In a compliant DOM API, there is nothing you need to do. Simply save actual newline characters to the attribute, the API will encode them correctly on its own (see Canonical XML spec, section 5.2).

If you do your own encoding (i.e. replacing \n with 
 before saving the attribute value), the API will encode your input again, resulting in 
 in the XML file.

Bottom line is, the value string is saved verbatim. You get out what you put in, no need to interfere.

However… some implementations are not compliant. For example, they will encode & characters in attribute values, but forget about newline characters or tabs. This puts you in a losing position since you can't simply replace newlines with 
 beforehand.

These implementations will save newline characters unencoded, like this:

<xml attribute="line 1
line 2" />

Upon parsing such a document, literal newlines in attributes are normalized into a single space (again, in accordance to the spec) - and thus they are lost.

Saving (and retaining!) newlines in attributes is impossible in these implementations.

Tomalak