0

I have an XML file which might be empty or already partially populated and I'm given an XPath in which I should insert some more xml nodes. Which is the cleaner way to create all the child nodes needed? In my mind, I'd like to find something like the mkdirs() method of the java.io.File class.

Example, given the XPath /root/child/grandson the expected output would be (based on an empty input file):

<root>
    <child>
        <grandson></grandson>
    </child>
</root>

Edit: I've for now managed to solve my simple use case by splitting the XPath and by nesting the nodes, any other cleaner solution would be appreciated.

1 Answer 1

1

If the paths are all as simple as this (a sequence of element names separated by slashes) then it can be done in XQuery or XSLT with a recursive function. In XQuery syntax:

declare function local:generate($names as xs:string*) as element(*) {
   if (exists($names)) then
      element{head($names)}{local:generate(tail($names)}
   else ()
};
local:generate(tokenize("/root/child/grandson", "/")[.]);

Explanation: first split the string on "/" boundaries; eliminate empty strings using the predicate [.]; pass the resulting sequence of strings to a function that creates an element named after the first string in the list, and then calls itself to process the rest of the list, attaching the result as the content of the created element.

Sign up to request clarification or add additional context in comments.

1 Comment

I ended up doing almost the same, but directly in Java

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.