2012-07-24 44 views
0

我需要选择Property1和SubProperty2并去除任何其他属性。我需要做出这个未来的证明,以便任何添加到xml的新属性都不会破坏验证。喵的新领域必须被剥离默认。在使用XSLT选择属性时遇到困难

<Root> 
    <Property1/> 
    <Property2/> 
    <Thing> 
     <SubProperty1/> 
     <SubProperty2/> 
    </Thing> 
    <VariousProperties/> 
</Root> 

所以在我的XSLT我这样做:

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

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

<xsl:template match="*" /> 

最后一行应该剥夺任何东西我还没有确定被选中。

这可以选择我的property1,但它总是为SubProperty选择一个空节点。 *之前的比赛似乎会在比赛结束之前剥离更深的对象,以便他们能够正常工作。 我删除了*上的匹配,并选择了具有值的SubProperty。那么,如何选择子属性,然后将所有我不使用的东西去掉。

感谢您的任何建议。

+0

没关系......我想通了,怎么办,我需要什么? – user1549583 2012-07-24 19:35:54

回答

0

有两个问题

<xsl:template match="*"/> 

这忽略了其中没有一个压倒一切的,更具体的模板的任何元素。

因为顶部元素Root没有特定的模板,所以它会被忽略以及它的所有子树 - 这是完整的文档 - 根本没有输出。

第二个问题是在这里

<xsl:template match="/Thing"> 

这个模板命名Thing顶部元素相匹配。

但是,在提供的文档中,顶层元素名为Root。因此,上述模板与提供的XML文档中的任何节点都不匹配,并且从不选择执行。由于其正文中的代码应该生成SubProperty1,因此不会生成此类输出。

解决方案

变化

<xsl:template match="*"/> 

<xsl:template match="text()"/> 

和更改

<xsl:template match="/Thing"> 

<xsl:template match="Thing"> 

整个改造成为

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

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

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

    <xsl:template match="text()" /> 
</xsl:stylesheet> 

当在下面的XML文档应用(如提供的是严重畸形的它不得不被修复):

<Root> 
    <Property1/> 
    <Property2/> 
    <Thing> 
     <SubProperty1/> 
     <SubProperty2/> 
    </Thing> 
    <VariousProperties/> 
</Root> 

现在的结果是什么都想

<Property1/> 
<SubProperty1/>