首页 > 解决方案 > XSLT 缺少的元素并未全部添加

问题描述

我的 XSLT 没有添加所有缺失的元素。我需要把这些领域和

这是我正在使用的 XML。

<Report>
   <Table>
      <ID>4</ID>
      <Name>R2D2</Name>
   </Table>
   <Table>
      <ID>0</ID>
      <Name>T1000</Name>
   </Table>
</Report>

这是 XSLT。(如果可能,我想使用 XSLT 2 或 3)

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="xml" indent="yes"/>

 <xsl:template match="node()">
  <xsl:copy>
    <xsl:apply-templates select="node()"/>
  </xsl:copy>
 </xsl:template>
<xsl:template match="Table[not(Address)]">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <Address/>
    </xsl:copy>
</xsl:template>
<xsl:template match="Table[not(City)]">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
        <City/>
    </xsl:copy>
</xsl:stylesheet>

由于某种原因地址丢失,我得到了这个结果!

<Report>
   <Table>
      <ID>4</ID>
      <Name>RD2</Name>
      <City/>
   </Table>
   <Table>
      <ID>0</ID>
      <Name>ZZZZ</Name>
      <City/>
   </Table>
</Report>

我期待得到这样的结果。此处如果地址和城市缺失,则包括在内。

<Report>
   <Table>
      <ID>4</ID>
      <Name>RD2</Name>
      <Address/>
      <City/>
   </Table>
   <Table>
      <ID>0</ID>
      <Name>ZZZZ</Name>
      <Address/>
      <City/>
   </Table>
</Report>

标签: xmlxslt

解决方案


由于某种原因,地址丢失!

地址丢失,因为没有地址和城市的表格与您的所有三个模板匹配,其中两个具有相同的优先级 - 仅应用了最后一个 - 请参阅:https ://www.w3.org/ TR/xslt20/#冲突

这是您可以解决此问题的一种方法:

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"/>

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

<xsl:template match="Table[not(Address and City)]">
    <xsl:copy>
        <xsl:apply-templates/>
        <xsl:if test="not(Address)">
            <Address/>
        </xsl:if>
        <xsl:if test="not(City)">
            <City/>
        </xsl:if>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

推荐阅读