Search code examples
xpathparent-childancestor

Wrapping an XML element with its ancestor nodes/tags


I can't navigate the XML doc programmatically and I need an one-line XPath solution for reasons I describe at the end.

I am working with an XML schema that looks something like the one below. (This is something I have to use as-is.)

<Root>
  <!-- Child 1 -->
  <Child>
      <Name>Joe</Name>
      <Age>12</Age>
  </Child>
  <!-- Child 2 -->
  <Child>
      <Name>Mike</Name>
      <Age>25</Age>
  </Child>
   <!-- Child 3 --> 
  <Child>
      <Name>Jane</Name>
      <Age>20</Age>
  </Child>
</Root>

Assuming I'm already at the "Joe" node (i.e. the Name element inside Child 1), I need to define an XPath query that will "wrap" that node as follows:

<Root>
  <!-- Child 1 -->
  <Child>
      <Name>Joe</Name>
      <Age>12</Age>
  </Child>
</Root>

I've tried various combinations of ancestor, string-join, concat, etc., but can't seem to find the solution that "wraps" the element correctly. (The way I was using ancestor was returning all Child nodes, for example, which is not what I need.)

Some other considerations:

  1. The solution has to be a one-line XPath query, if that's possible (for reasons given below).
  2. It has to be generic enough to work for any Child element (i.e., it can't assume that I'm always at the first or second or third child, for example).
  3. From the example above, you can see that I don't actually need the actual Root node per-se, just its tag (i.e. I don't want all Child nodes under it). However, I do need the actual Child node (so that I get the Name and Age).

NOTE: For what it's worth, I can't actually navigate the XML programmatically. I am using a library (whose code I cannot change) in which I have to define everything in terms of one-line XPath queries within a configuration file. It will essentially navigate through all of the Name elements, so my solution has to work from that point.


Solution

  • XPath is a query language.

    This, among other things means that the evaluation of an XPath expression never modifies the XML document.

    So, the answer is: Modifying an XML document or creating a new document cannot be done using only XPath.

    Such transformations are very easy and natural to specify with XSLT.