Can XPath group a selected node list by intermediate nodes?

Viewed 55

I have the following XML string:

<?xml version="1.0" encoding="UTF-8"?>
<a>
  <b>
    <c>r</c>
    <c>s</c>
    <c>t</c>
  </b>
  <b>
    <c>u</c>
    <c>v</c>
    <c>w</c>
  </b>
  <b>
    <c>x</c>
    <c>y</c>
    <c>z</c>
  </b>
</a>

With an XPath query of "a/b/c/text()" I can extract a list easily:

[ r, s, t, u, v, w, x, y, z ]

Is it possible to get the result grouped by the level 'b' like this:

[
  [ r, s, t ],
  [ u, v, w ],
  [ x, y, z ] 
]

fiddle

1 Answers

No, XPath alone cannot produce a list of lists of strings:

  • XPath 1.0's nodesets are never nested.
  • XPath 2.0/3.1's sequences are never nested.

In general, XPath is for selection, not transformation. In your first example, XPath selects a list of text nodes and presents them as a list of string values.

To further transform the nodes selected by one or more XPath expressions, employ the general programming facilities of the hosting language (XSLT, Python, JavaScript, etc).


Update: Per your comment, you indicate that a lexical representation of the desired grouping would suffice. Yes, you could compose the targeted output via string functions:

XPath 2.0

concat('[', 
       string-join(for $b in /a/b
                       return concat('[',string-join($b/c,','),']'),
                   ','),
       ']')
Related