xsl模板匹配精确节点

时间:2014-01-09 08:49:26

标签: xslt xml-namespaces

我是xslt的首发,我坚持这个:

abc.xml

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ns2:procesResponse xmlns:ns2="http://schemas.com/2014/generic">
      <a>
        <b>
          <c>
            <d>test</d>
            <e>someValue</e>
          </c>
        </b>
        <b>
          <c>
            <d>test 2</d>
            <e>someValue</e>
          </c>
        </b>
        <b>
          <c>
            <d>test</d>
            <e>someValue</e>
          </c>
        </b>
      </a>
    </ns2:procesResponse>
  </soap:Body>
</soap:Envelope>

到目前为止我做了什么:

doit.xsl

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="/">
    <something>
      <stillSomething>
        <Author>administrator</Author>
        <Version>V1_4</Version>
        <Date>09012014</Date>
      </stillSomething>
      <values>
        <xsl:apply-templates select="Envelope/Body/procesResponse/a/b/c" />
      </values>
    </something>
  </xsl:template>
    <xsl:template match="Envelope/Body/procesResponse/a/b/c">
      <result>succeeded</result>
  </xsl:template>
</xsl:stylesheet>
xsltproc执行后的

结果:

为result.xml

<something>
  <stillSomething>
    <Author>administrator</Author>
    <Version>V1_4</Version>
    <Date>09012014</Date>
  </stillSomething>
  <values/>
</something>

但我想得到这个:

<something>
  <stillSomething>
    <Author>administrator</Author>
    <Version>V1_4</Version>
    <Date>09012014</Date>
  </stillSomething>
  <values>
    <result>succeeded</result>
    <result>succeeded</result>
    <result>succeeded</result>
  </values>
</something>

成功找到三个节点后应该有三次。

我知道问题在于这两行:

<xsl:apply-templates select="Envelope/Body/procesResponse/a/b/c" />

<xsl:template match="Envelope/Body/procesResponse/a/b/c">

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

这里最大的问题是无法正确使用名称空间。一旦它们在XSLT中声明并在XPath中使用,那么这将产生预期的结果:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
                xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
                xmlns:ns2="http://schemas.com/2014/generic"
                exclude-result-prefixes="soap ns2">
  <xsl:template match="/">
    <something>
      <stillSomething>
        <Author>administrator</Author>
        <Version>V1_4</Version>
        <Date>09012014</Date>
      </stillSomething>
      <values>
        <xsl:apply-templates 
           select="soap:Envelope/soap:Body/ns2:procesResponse/a/b/c" />
      </values>
    </something>
  </xsl:template>
  <xsl:template match="c">
    <result>succeeded</result>
  </xsl:template>
</xsl:stylesheet>

结果:

<something>
  <stillSomething>
    <Author>administrator</Author>
    <Version>V1_4</Version>
    <Date>09012014</Date>
  </stillSomething>
  <values>
    <result>succeeded</result>
    <result>succeeded</result>
    <result>succeeded</result>
  </values>
</something>