【问题标题】:XSLT How to create xml tags from from rich text dataXSLT 如何从富文本数据创建 xml 标签
【发布时间】:2018-09-06 05:41:58
【问题描述】:

我正在使用 xsl 将 xml 转换为 xml。你能帮我写个xsl代码来把输入转换成输出吗?

给定输入:

    <ATTRIBUTE-VALUE>
    <THE-VALUE>
        <div xmlns="http://www.w3.org/1999/xhtml">
            <h1 dir="ltr" id="_1536217498885">Main Description</h1>
            <p>The main description text goes here.</p>
            <h1 dir="ltr" id="_1536217498886">Key Consideration</h1>
            <p>The key consideration text goes here.</p>
            <h1 dir="ltr" id="_1536217498887">Skills</h1>
            <p>The Skills text goes here.</p>
            <h1 dir="ltr" id="_1536217498888">Synonyms</h1>
            <p>The Synonyms text goes here.</p>
        </div>
    </THE-VALUE>
</ATTRIBUTE-VALUE>

预期输出:

<MainDescription><![CDATA[The main description text goes here.]]></MainDescription>
<KeyConsiderations><![CDATA[The key consideration text goes here.]]></KeyConsiderations>
<Skills>The skills text goes here.</Skills>
<Synonyms>The synonyms text goes here.</Synonyms>

【问题讨论】:

  • 我对 xslt 很陌生。谁能提供 xslt-1.0 的解决方案?

标签: xml xslt xslt-2.0 xslt-grouping xslt-3.0


【解决方案1】:

尝试以下操作(前缀“x”绑定到 xhtml 命名空间)

<xsl:template match="THE-VALUE/x:div">
<xsl:for-each-group select="*" group-starting-with="x:h1">
  <xsl:element name="{translate(current-group()[1], ' ', '')}">
    <xsl:value-of select="current-group()[2]"/>
  </xsl:element>
</xsl:for-each-group>
</xsl:template> 

实际上这并不需要分组:您同样可以使用&lt;xsl:for-each select="h1"&gt;,然后将组中的两个元素分别称为.following-sibling::p[1]。那就是:

  <xsl:template match="THE-VALUE/x:div">
    <xsl:for-each select="x:h1">
      <xsl:element name="{translate(., ' ', '')}">
        <xsl:value-of select="following-sibling::*[1]"/>
      </xsl:element>
    </xsl:for-eac>
  </xsl:template> 

后一种解决方案适用于 XSLT 1.0。

【讨论】:

  • 如何将值作为富文本放在 CDATA 下?
  • 当我使用 xsl:template current-group()[2] 时给出错误无效的 xpath。如何解决?另外,应该在模板中添加什么以在 CDATA 中插入值?
  • 如果 current-group()[2] 给出错误,那么您可能正在使用 XSLT 1.0 处理器。我给了你一个 2.0 的答案,因为你标记了问题 xslt 2.0。
  • 所需输出中的 CDATA 标记完全没有意义,反映了对 XML 的理解不足。但是,如果您真的认为自己需要它们,请使用 xsl:output/@cdata-section-elements
  • 我对 xslt 很陌生。您能否在 xslt-1.0 中提供解决方案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 1970-01-01
相关资源
最近更新 更多