count of element in XPath

前端 未结 3 1780
一整个雨季
一整个雨季 2021-02-02 07:52
...

     ... 
     ... 
    

        
相关标签:
3条回答
  • 2021-02-02 08:43

    You can try the following:

    count(//element/Element1[namespace-uri()='mynamespace'])
    
    0 讨论(0)
  • 2021-02-02 08:45

    If you are using XPath from an environment such as Java or C#, you should first bind a prefix to the namespace, which depends on the API you are using, but will be something like

    xpath.declareNamespace("f", "mynamespace")
    

    and then evaluate the XPath expression

    count(element/f:Element1)
    

    I deliberately chose a different prefix from the one in your source document just to show that you can use any prefix you like, but of course your code is more readable if you are consistent in your choice of prefixes.

    0 讨论(0)
  • 2021-02-02 08:48

    For the following valid XML

    <element>
      <e:Element1 xmlns:e="mynamespace"></e:Element1>
      <e:Element1 xmlns:e="mynamespace"></e:Element1>
      <e:Element1 xmlns:e="mynamespace"></e:Element1>
      <a/>
    </element>
    

    this XSL

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:e="mynamespace">
    <xsl:template match="/">
        <xsl:value-of select="count(element/e:Element1)"/>
    </xsl:template>
    </xsl:stylesheet>
    

    gives the desired output of 3.

    The selector is qualified with the correct namespace.

    You were close in your question and you could drop the namespace and use the following XSL instead:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <xsl:value-of select="count(element/*[local-name()='Element1'])"/>
    </xsl:template>
    </xsl:stylesheet>
    
    0 讨论(0)
提交回复
热议问题