无法通过 XSLT 在属性值中插入换行符

Cannot insert line break in attribute value via XSLT

我是 XSLT 的新手,我很难在两个句子之间插入换行符。我知道论坛上有人问过类似的问题,但 none 的解决方案对我有用,如果我违反了任何社区规则,我深表歉意。

所以基本上我有这样的东西:

<xsl:attribute name="messageText">
<xsl:value-of select="eligInformation/@messageText02"/>
<br />
<xsl:value-of select="eligInformation/@messageText03"/>
</xsl:attribute>    

但是 <br /> 或其任何变体(<br/>, <br></br> 等)无法正常工作,.NET 解析器似乎不喜欢它并抛出以下错误:“An类型 'Element' 的项目不能在类型 'Attribute'" 的节点中构造。

我也尝试过各种替代方案,例如:

<xsl:text>&#xa;</xsl:text>
<xsl:text>&#10;</xsl:text>
<xsl:text>

</xsl:text>

等等,但在那些情况下,即使我没有收到任何错误,两条消息也只是出现在同一行中。

xsl:attribute用于设置属性值。

<br/> 是一个 HTML 元素,属性值中不允许元素,因此出现您报告的错误消息。

虽然 XML 属性中允许使用换行符,但此类设计或计划很可能 运行 由于对 3.3.3 Attribute-Value Normalization 的不正确、不一致甚至正确的解释而搁浅:

3.3.3 Attribute-Value Normalization

Before the value of an attribute is passed to the application or checked for validity, the XML processor must normalize the attribute value by applying the algorithm below, or by using some other method such that the value passed to the application is the same as that produced by the algorithm.

  1. All line breaks must have been normalized on input to #xA as described in 2.11 End-of-Line Handling, so the rest of this algorithm operates on text normalized in this way.

  2. Begin with a normalized value consisting of the empty string.

  3. For each character, entity reference, or character reference in the unnormalized attribute value, beginning with the first and continuing to the last, do the following:

    • For a character reference, append the referenced character to the normalized value.

    • For an entity reference, recursively apply step 3 of this algorithm to the replacement text of the entity.

    • For a white space character (#x20, #xD, #xA, #x9), append a space character (#x20) to the normalized value.

For another character, append the character to the normalized value.

建议:避免在 XML 属性值中换行。

另见

  • Are line breaks in XML attribute values allowed?
  • How to save newlines in XML attribute?

不清楚您如何将 XSLT 与 .NET 一起使用,但如果您将字符引用放在属性值中,那么它应该被序列化,例如在 https://xsltfiddle.liberty-development.net/nb9PtDz XML

<root>
    <item info1="Line 1." info2="Line 2."/>
</root>

改造
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="item">
      <item infos="{@info1}&#10;{@info2}"/>
  </xsl:template>

</xsl:stylesheet>

在结果中使用 .NET 的 XslCompiledTransform

<root>
    <item infos="Line 1.&#xA;Line 2." />
</root>

所以 LF 在那里,它必须作为字符引用进行转义,否则,任何解析结果的 XML 解析器都会将正常的 LF 转换为属性规范化的 space。