如何在 XML 属性中保存换行符? [英] How to save newlines in XML attribute?

查看:42
本文介绍了如何在 XML 属性中保存换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保存在某些 XML 属性中包含换行符的内容,而不是文本.应该选择该方法,以便我能够在 XSLT 1.0/ESXLT/XSLT 2.0 中对其进行解码

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.

推荐答案

在兼容的 DOM API 中,您无需执行任何操作.只需将实际的换行符保存到属性中,API 就会自行对它们进行正确编码(参见 规范 XML 规范,第 5.2 节).

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).

如果您自己编码(即在保存属性值之前将 替换为 
),API 将对您的输入进行编码 再次,在 XML 文件中生成 
.

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

最重要的是,字符串值是逐字保存的.你把你放进去的东西拿出来,不需要干涉.

Bottom line is, the string value 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.

这篇关于如何在 XML 属性中保存换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆