首页 > 解决方案 > 使用 XSLT 从任何 xml 中提取所有文本节点的 xpath 值

问题描述

我有一个xml:

<root>
 <child attrib1="1">
  <subChild>
   <name>subChild1</name>
  </subChild>
 </child>
 <child attrib1="2>
  <subChild2>
   <name>subChild2</name>
  </subChild2>
 </child>

我希望 xslt 生成 o/p 如下,即 xpath 及其值:

  1. /root/child[@attrib1="1]/subChild/name="subChild1"
  2. /root/child[@attrib1="2]/subChild2/name="subChild2"

标签: xmlxslt

解决方案


如评论中所述,您的问题并不完全清楚。尝试这样的事情作为你的起点:

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:strip-space elements="*"/>

<xsl:template match="/">
    <xsl:for-each select="//text()">
        <xsl:apply-templates select="parent::*"/>
        <xsl:text>="</xsl:text>
        <xsl:value-of select="."/>
        <xsl:text>"&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

<xsl:template match="*">
    <xsl:apply-templates select="parent::*"/>
    <xsl:text>/</xsl:text>
    <xsl:value-of select="name()"/>
    <xsl:apply-templates select="@*"/>  
</xsl:template>

<xsl:template match="@*">
    <xsl:text>[@</xsl:text>
    <xsl:value-of select="name()"/>
    <xsl:text>="</xsl:text>
    <xsl:value-of select="."/>
    <xsl:text>"]</xsl:text>
</xsl:template>

</xsl:stylesheet>

推荐阅读