XPath to return string concatenation of qualifying child node values

只愿长相守 提交于 2019-11-26 09:45:00

问题


Can anyone please suggest an XPath expression format that returns a string value containing the concatenated values of certain qualifying child nodes of an element, but ignoring others:

<div>
    This text node should be returned.
    <em>And the value of this element.</em>
    And this.
    <p>But this paragraph element should be ignored.</p>
</div>

The returned value should be a single string:

This text node should be returned. And the value of this element. And this.

Is this possible in a single XPath expression?

Thanks.


回答1:


In XPath 1.0:

You can use

/div//text()[not(parent::p)]

to capture the wanted text nodes. The concatenation itself cannot be done in XPath 1.0, I recommend doing it in the host application.




回答2:


In XPath 2.0 :

string-join(/*/node()[not(self::p)], '')




回答3:


/div//text()

double slash forces to extract text regardless of intermediate nodes




回答4:


This look that works:

Using as context /div/:

text() | em/text()

Or without the use of context:

/div/text() | /div/em/text()

If you want to concat the first two strings, use this:

concat(/div/text(), /div/em/text())



回答5:


If you want all children except p, you can try the following...

    string-join(//*[name() != 'p']/text(), "")

which returns...

This text node should be returned.
And the value of this element.
And this.



回答6:


You could use a for-each loop as well and assemble the values in a variable like this

<xsl:variable name="newstring">
    <xsl:for-each select="/div//text()">
      <xsl:value-of select="."/>
    </xsl:for-each>
  </xsl:variable>


来源:https://stackoverflow.com/questions/1403971/xpath-to-return-string-concatenation-of-qualifying-child-node-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!