xslt – 列出XML文件中的每个节点

前端之家收集整理的这篇文章主要介绍了xslt – 列出XML文件中的每个节点前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
简单的情况……对于任何随机的XML文件,我想创建一个包含它的每个节点的列表,但没有任何重复!所以类似于:
  1. <root name="example">
  2. <child id="1">
  3. <grandchild/>
  4. </child>
  5. <child id="2"/>
  6. <child id="3"/>
  7. </root>

被翻译成:

  1. /root
  2. /root/@name
  3. /root/child
  4. /root/child/@id
  5. /root/child/grandchild

如何通过使用XSLT来做到这一点?

只是为了好玩,没有扩展功能.
  1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  2. <xsl:template match="text()"/>
  3. <xsl:template match="*|@*">
  4. <xsl:param name="pPath"/>
  5. <xsl:param name="pNames" select="'&#xA;'"/>
  6. <xsl:variable name="vPath"
  7. select="concat($pPath,'/',substring('@',1 div (count(.|../@*) =
  8. count(../@*))),name())"/>
  9. <xsl:variable name="vNames">
  10. <xsl:if test="not(contains($pNames,concat('&#xA;',$vPath,'&#xA;')))">
  11. <xsl:value-of select="concat($vPath,'&#xA;')"/>
  12. </xsl:if>
  13. <xsl:apply-templates select="*[1]|@*">
  14. <xsl:with-param name="pPath" select="$vPath"/>
  15. <xsl:with-param name="pNames" select="$pNames"/>
  16. </xsl:apply-templates>
  17. </xsl:variable>
  18. <xsl:value-of select="$vNames"/>
  19. <xsl:apply-templates select="following-sibling::*[1]">
  20. <xsl:with-param name="pPath" select="$pPath"/>
  21. <xsl:with-param name="pNames" select="concat($pNames,$vNames)"/>
  22. </xsl:apply-templates>
  23. </xsl:template>
  24. </xsl:stylesheet>

输出

  1. /root
  2. /root/@name
  3. /root/child
  4. /root/child/@id
  5. /root/child/grandchild

编辑:XSLT / XPath 2.0的更好示例.这个XPath 2.0行:

  1. string-join(
  2. distinct-values(
  3. (//*|//@*)
  4. /string-join(
  5. (ancestor::node()/name(),if (self::attribute())
  6. then concat('@',name())
  7. else name()),'/')),'&#xA;')

猜你在找的XML相关文章