2012-06-12 42 views
2

有沒有一種簡單的方法,可能使用Linux中的開源命令行工具,從給定的XML文檔中剝離給定閾值之外的所有級別,而不管結構如何?返回到第n級的XML結構

輸入:

<a att="1"> 
    <b/> 
    <c bat="2"> 
     <d/> 
    </c> 
</a> 

輸出,電平= 1:

<a att="1"/> 

輸出,級別= 2:

<a att="1"> 
    <b/> 
    <c bat="2"/> 
</a> 

我曾嘗試的XPath,但無法以限制電平。

回答

3

在XSLT很簡單:

<xsl:template match="*"> 
    <xsl:if test="count(ancestor::*) &lt;= $level"> 
    <xsl:copy> 
     <xsl:copy-of select="@*"/> 
     <xsl:apply-templates/> 
    </xsl:copy> 
    </xsl:if> 
</xsl:template> 
+0

謝謝。在添加'聲明後適用於我。 – krlmlr

3

在XQuery中它幾乎等同於XSLT:

copy $output := $input 
modify delete nodes $output//node()[count(ancestor::*) eq $level] 
return $output 

try it with zorba

2

或者沒有XQuery更新,解構和重新組裝起來的樹直到達到最高水平:

declare function local:limit-level($element as element(), $level as xs:integer) { 
    if ($level gt 0) 
    then 
     element {node-name($element)} { 
      $element/@*, 
     (
     for $child in $element/node() 
     return local:limit-level($child, $level - 1) 
    ) 
    } 
    else() 
}; 

local:limit-level(/*, 2)