简体   繁体   中英

Populate XML file from XPath in Java

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM