2015-08-15 34 views
1

我試圖找到一種方法將XML標記轉換爲各自的唯一地址,如xPath。釹我找到了一個XSLT,其中處理XML,並且唯一的地址僅爲沒有子元素和屬性的節點創建。 [鏈接]:Generate/get xpath from XML node java使用XSLT爲所有節點生成XML的xpath

XSLT:

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

    <xsl:variable name="vApos">'</xsl:variable> 

    <xsl:template match="*[@* or not(*)] "> 
     <xsl:if test="not(*)"> 
     <xsl:apply-templates select="ancestor-or-self::*" mode="path"/> 
     <xsl:value-of select="concat('=',$vApos,.,$vApos)"/> 
     <xsl:text>&#xA;</xsl:text> 
     </xsl:if> 
     <xsl:apply-templates select="@*|*"/> 
    </xsl:template> 

    <xsl:template match="*" mode="path"> 
     <xsl:value-of select="concat('/',name())"/> 
     <xsl:variable name="vnumPrecSiblings" select= 
     "count(preceding-sibling::*[name()=name(current())])"/> 
     <xsl:if test="$vnumPrecSiblings"> 
      <xsl:value-of select="concat('[', $vnumPrecSiblings +1, ']')"/> 
     </xsl:if> 
    </xsl:template> 

    <xsl:template match="@*"> 
     <xsl:apply-templates select="../ancestor-or-self::*" mode="path"/> 
     <xsl:value-of select="concat('[@',name(), '=',$vApos,.,$vApos,']')"/> 
     <xsl:text>&#xA;</xsl:text> 
    </xsl:template> 
</xsl:stylesheet> 

傳遞給這個

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <main> 
     <tag1>001</tag1> 
     <tag2>002</tag2> 
     <tag3> 
     <tag4>004</tag4> 
     </tag3> 
     <tag2>002</tag2> 
     <tag5>005</tag5> 
    </main> 
</root> 

時產生

/root/main/tag1='001' /root/main/tag2='002' /root/main/tag3/tag4='004' /root/main/tag2[2]='002' /root/main/tag5='005' 

所以我需要的XSLT通過以下方式產生

/root 
/root/main 
/root/main/tag1 
/root/main/tag2 
/root/main/tag3 
/root/main/tag3/tag4 
/root/main/tag2[2] 
/root/main/tag5 

另外我不需要價值觀。所以,請幫助我這個

回答

2

你的結果可能是相當簡單的製作:

XSLT 1.0

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output method="text" encoding="UTF-8"/> 

<xsl:template match="*"> 
    <xsl:for-each select="ancestor-or-self::*"> 
     <xsl:value-of select="name()" /> 
     <xsl:variable name="i" select="count(preceding-sibling::*[name()=name(current())])"/> 
     <xsl:if test="$i"> 
      <xsl:value-of select="concat('[', $i + 1, ']')"/> 
     </xsl:if> 
     <xsl:if test="position()!=last()"> 
      <xsl:text>/</xsl:text> 
     </xsl:if> 
    </xsl:for-each> 
    <xsl:text>&#10;</xsl:text> 
    <xsl:apply-templates select="*"/> 
</xsl:template> 

</xsl:stylesheet> 

請注意,這並不進程屬性(或任何其他類型的比其他節點元件)。

+0

謝謝邁克爾......完美地工作...... –

+1

@DilipNs如果您的問題得到解答,請通過接受答案關閉它。 –