如果"匹配"其他

时间:2014-11-19 16:28:35

标签: xml xslt xslt-1.0 xslt-2.0

在XSLT中,我经常使用以下命令匹配节点

<xsl:template match="*[local-name() = 'Proposal']/*[local-name() = 'ApplicationData']">

将从

获取节点
<?xml version="1.0" encoding="utf-8"?><?xfa generator="XFA2_4" APIVersion="2.8.9029.0"?>
    <xdp:xdp xmlns:xdp="http://ns.adobe.com/xdp/" timeStamp="2013-03-01T09:48:58Z" uuid="3e3468da-104d-4532-8077-0dc001ca166b">
       <xfa:datasets xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
          <xfa:data>
             <Proposal xmlns="http://www.govtalk.gov.uk/planning/OneAppProposal-2006" Version="">
                 <oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
                        <oneapp:TreesHedgesWales/>
                        <oneapp:OtherLowCarbonEnergy/>
                 </oneapp:ApplicationData>
             </Proposal>
         ...

匹配

<oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
      <oneapp:TreesHedgesWales/>
      <oneapp:OtherLowCarbonEnergy/>
 </oneapp:ApplicationData>

我如何确定ApplicationData是否存在,如果不存在,请插入它?

1 个答案:

答案 0 :(得分:1)

您需要将逻辑添加到与“提案”匹配的模板中。元件

<xsl:template match="*[local-name() = 'Proposal']">

然后,您只需编写xsl:if语句,如下所示:

<xsl:if test="not(*[local-name() = 'ApplicationData'])">
   <oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
      <oneapp:TreesHedgesWales/>
      <oneapp:OtherLowCarbonEnergy/>
   </oneapp:ApplicationData>
</xsl:if>

如果您想保留xsl:copy元素,则需要将其包装在Proposal中。

如果您在XSLT中没有匹配Proposal的现有模板,则可以将测试添加到模板匹配本身

<xsl:template match="*[local-name() = 'Proposal'][not(*[local-name() = 'ApplicationData'])]">
   <xsl:copy>
      <oneapp:ApplicationData xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">
          <oneapp:TreesHedgesWales/>
          <oneapp:OtherLowCarbonEnergy/>
      </oneapp:ApplicationData>
   </xsl:copy>
</xsl:template>

正如michael.hor257k在评论中提到的那样,如果你在XSLT中声明你的命名空间,并在匹配中使用名称空间前缀,它会更清晰。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
     xmlns:oneapp="http://www.govtalk.gov.uk/planning/OneAppProposal-2006">

<xsl:template match="oneapp:Proposal[not(oneapp:ApplicationData)]">
   <xsl:copy>
      <oneapp:ApplicationData>
         <oneapp:TreesHedgesWales/>
         <oneapp:OtherLowCarbonEnergy/>
      </oneapp:ApplicationData>
   </xsl:copy>
</xsl:template>