2011-03-17 45 views
0

我有一个an earlier post的解决方案,由Dimitre Novatchev友情提供。XSL匹配一些但不是全部

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my"> 
    <xsl:output method="xml" version="1.0" encoding="iso-8859-1" indent="yes"/> 
    <xsl:key name="kPhysByName" match="KB_XMod_Modules" use="Physician"/> 
    <xsl:template match="/"> 
    <result> 
     <xsl:apply-templates/> 
    </result> 
    </xsl:template> 
    <xsl:template match="/*/*/*[starts-with(name(), 'InfBy')]"> 
    <xsl:variable name="vCur" select="."/> 
    <xsl:for-each select="document('doc2.xml')"> 
     <xsl:variable name="vMod" select="key('kPhysByName', $vCur)"/> 
     <xsl:copy> 
     <items> 
      <item> 
      <label> 
       <xsl:value-of select="$vMod/Physician"/> 
      </label> 
      <value> 
       <xsl:value-of select="$vMod/XModID"/> 
      </value> 
      </item> 
     </items> 
     </xsl:copy> 
    </xsl:for-each> 
    </xsl:template> 
</xsl:stylesheet> 

我现在需要在我的源XML使用额外的领域和需要的现有标签完好,但我在得到这个持续存在的问题。

<instance> 
    <NewTag>Hello</newTag1> 
    <AnotherNewTag>Everyone</AnotherNewTag> 
    <InfBy1>Dr Phibes</InfBy1> 
    <InfBy2>Dr X</InfBy2> 
    <InfBy3>Dr Chivago</InfBy3> 
</instance> 

它植入额外的标签和产出

<result xmlns:my="my:my"> 
    HelloEveryone 
    <items> 
    <item> 
     <label>Dr Phibes</label> 
     <value>60</value> 
    </item> 
    </items> 
    ... 

我一直在尝试了很多与

<xsl:otherwise> 
    <xsl:copy-of select="."> 
    </xsl:copy-of> 
</xsl:otherwise> 

但作为一个xsl新手我似乎无法得到这个工作。我有一种感觉,我在吠叫错误的树!

有没有人有任何想法?

感谢,

+0

XPath表达式match =“/ */*/*”怎么样? – ThomasRS 2011-03-17 16:18:35

回答

2

NewTagAnotherNewTag元素由Built-in Template Rules匹配。如果你想要另一种转换,你需要声明这样的规则。

需要完整的现有标签

然后你正在寻找的identity rule

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

@Alejandro:谢谢亚历杭德罗 - 真的很有帮助! – Willb 2011-03-17 17:06:40

+0

@Willb:不客气。 – 2011-03-17 17:42:58

0

这是<xsl:apply-templates>它试图找到每个子节点的匹配模板的副作用它会遇到隐含的XSLT“默认行为”。

就你而言,它遇到了<NewTag><AnotherNewTag>,但这些节点没有模板。

捕获此案例的默认行为(隐藏的默认模板)将元素的文本值复制到输出流。

<NewTag>的文本值为“Hello”,<AnotherNewTag>的文本值为“Everyone”,所以您会看到“HelloEveryone”。

如果你不希望这样,写自己的模板,捕捉这些节点:

<xsl:template match="NewTag|AnotherNewTag"> 
    <xsl:copy-of select="." /> 
</xsl:template> 

或者,写一个映入任何未处理的元素节点:

<!-- empty templates do nothing (matched nodes do not appear in the output) --> 
<xsl:template match="*" /> 

如果你想要复制未处理的节点,但仍想递归地在其中应用模板,身份模板(@ Alejandro的答案显示它)是要走的路。

+0

感谢您的解释。我确实需要循环访问一些记录,并且使用@ Alejandro的解决方案。 – Willb 2011-03-17 17:06:57

相关问题