首页 > 解决方案 > 在循环中将 CDATA 添加到节点值

问题描述

** 更新了输出 ** 我正在尝试将 <![CDATA[...]] 添加到循环内生成的值节点。我正在使用 XSLT 和 C#.net。我已经尝试了几件事,包括 将 CDATA 添加到 xml 文件 ,但到目前为止似乎没有任何工作。我什至尝试按字面意思添加它,但正如预期的那样,它没有成功。任何人都可以在这方面帮助我。

这是我的节点的生成方式

<xsl:for-each select="$OLifE/">
                    <DataPoint>
                      <Name>Carrier.Requirements<xsl:if test="$NumberOfPayments > 1"><xsl:value-of select="position()"/></xsl:if></Name>
                      <Value>Here is the response text</Value>
</DataPoint>

我的预期输出是

<DataPoint>
    <Name>Carrier.Requirements1</Name>
    <Value><![CDATA[Here is the response text]]</Value>
</DataPoint>
<DataPoint>
    <Name>Carrier.Requirements2</Name>
    <Value><![CDATA[Here is the response text]]</Value>
</DataPoint>
<DataPoint>
    <Name>Carrier.Requirements3</Name>
    <Value><![CDATA[Here is the response text]]</Value>
</DataPoint>

如果需要任何进一步的信息,请告诉我。

标签: c#xsltcdata

解决方案


这是一个简化的示例:

XML

<input>
    <item/>
    <item/>
    <item/>
</input>

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" cdata-section-elements="Value"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/input">
    <output>
        <xsl:for-each select="item">
            <DataPoint>
                <Name>
                    <xsl:value-of select="concat('Carrier.Requirements', position())"/>
                </Name>
                <Value>Here is the response text</Value>
            </DataPoint>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

结果

<?xml version="1.0" encoding="utf-16"?>
<output>
  <DataPoint>
    <Name>Carrier.Requirements1</Name>
    <Value><![CDATA[Here is the response text]]></Value>
  </DataPoint>
  <DataPoint>
    <Name>Carrier.Requirements2</Name>
    <Value><![CDATA[Here is the response text]]></Value>
  </DataPoint>
  <DataPoint>
    <Name>Carrier.Requirements3</Name>
    <Value><![CDATA[Here is the response text]]></Value>
  </DataPoint>
</output>

演示https ://xsltfiddle.liberty-development.net/94hvTAn


推荐阅读