Reputation: 12426
I would like to use XQuery to generate Java source code from my XML document, for instance:
<configuration package="my.package.name">
<property>
<name>First</name>
<value>0</value>
<description>First description</description>
</property>
<property>
<name>Second</name>
<value>2</value>
<description>Second description</description>
</property>
...
Should generate:
package my.package.name;
class MyClass {
// First description
private String first;
// Second description
private String second;
}
I was trying to start like this:
xquery version "1.0";
"package "+$doc/@package
"class "+$doc/@classname
{
for $property in $doc//property
return {
"private String "+$property/name::text()
}
}
The syntax is obviously incorrect and I wonder whether it is even feasible. Thanks!
Upvotes: 1
Views: 330
Reputation: 736
XQuery:
declare function xf:XML2Java($configuration as element(configuration))
as xs:string {
let $package := string($configuration/@package)
let $newline := " "
for $property in $configuration/property
let $variable := data($property/name)
let $javadoc := data($property/description)
return
fn:concat($package,$newline,"class MyClass{",$newline,"//",$javadoc,$newline,"private String ",$variable,";",$newline," }")
};
Input:
<configuration package="com.test">
<property>
<name>Test</name>
<value>somevalue</value>
<description>This is test variable</description>
</property>
</configuration>
Output:
com.test
class MyClass{
//This is test variable
private String Test;
}
Did this in WebLogic workshop XQuery designer.
Upvotes: 1
Reputation: 163665
The details depend a bit on your query processor. It should be possible to return a query result as a string, and it may also be possible to use the text serialization method as in XSL; but the way you invoke this varies from one query processor to another. (The difference between the two approaches is that the text serialization method will automatically turn anything in the query result into a string, and then concatenate the strings).
Here's how to do it in the form of a query returning a single string:
declare variable $nl "= ' ';
concat(
"package ", $doc/@package, $nl,
"class ", $doc/@classname, $nl,
string-join(
(for $property in $doc//property
return {
concat("private String ", $property/name)
}), $nl)
)
Upvotes: 1