3

htmlを定義するxmlドキュメントをhtml形式に変換するための非常に単純なxslスタイルシートがあります(理由を聞かないでください、それは私たちがしなければならない方法です...)

<xsl:template match="/">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="HtmlElement">
  <xsl:element name="{ElementType}">
    <xsl:apply-templates select="Attributes"/>
    <xsl:value-of select="Text"/>
    <xsl:apply-templates select="HtmlElement"/>
  </xsl:element>
</xsl:template>

<xsl:template match="Attributes">
  <xsl:apply-templates select="Attribute"/>
</xsl:template>

<xsl:template match="Attribute">
  <xsl:attribute name="{Name}">
    <xsl:value-of select="Value"/>
  </xsl:attribute>
</xsl:template>

この問題は、変換が必要なHTMLのこの小さな部分に出くわしたときに発生しました。

<p>
      Send instant ecards this season <br/> and all year with our ecards!
</p>

真ん中の<br/>は変換のロジックを壊し、段落ブロックの前半だけを表示しますSend instant ecards this season <br></br>。変換しようとしているXMLは次のようになります。

<HtmlElement>
    <ElementType>p</ElementType>
    <Text>Send instant ecards this season </Text>
    <HtmlElement>
      <ElementType>br</ElementType>
    </HtmlElement>
    <Text> and all year with our ecards!</Text>
</HtmlElement>

提案?

4

2 に答える 2

1

Text 要素に新しいルールを追加するだけで、HTMLElements と Texts の両方に一致させることができます。

<xsl:template match="HtmlElement">
  <xsl:element name="{ElementName}">
    <xsl:apply-templates select="Attributes"/>
    <xsl:apply-templates select="HtmlElement|Text"/>
  </xsl:element>
</xsl:template>

<xsl:template match="Text">
    <xsl:value-of select="." />
</xsl:template>
于 2013-01-04T22:44:51.647 に答える
0

テンプレートを調整して追加の要素を処理するために、スタイルシートをもう少し一般的なものにすることができます。HtmlElementテンプレートを最初に要素に適用し、次にselect 属性の述語フィルターを使用して and要素を除くAttributesすべての要素に適用します。の。AttributesHtmlElementxsl:apply-templates

組み込みのテンプレートはText要素と一致し、出力にコピーしtext()ます。

また、現在宣言しているルート ノードのテンプレート (つまりmatch="/") を削除することもできます。組み込みのテンプレート ルールによって既に処理されているものを再定義するだけで、動作を変更することは何もせず、スタイルシートを乱雑にするだけです。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output indent="yes"/>

<!--    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>-->

    <xsl:template match="HtmlElement">
        <xsl:element name="{ElementType}">
            <xsl:apply-templates select="Attributes"/>
            <!--apply templates to all elements except for ElementType and Attributes-->
            <xsl:apply-templates select="*[not(self::Attributes|self::ElementType)]"/>
        </xsl:element>
    </xsl:template>

    <xsl:template match="Attributes">
        <xsl:apply-templates select="Attribute"/>
    </xsl:template>

    <xsl:template match="Attribute">
        <xsl:attribute name="{Name}">
            <xsl:value-of select="Value"/>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>
于 2013-01-05T14:33:40.053 に答える