1

我想使用 XQuery 从我的 XML 文档生成 Java 源代码,例如:

<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>
...

应该生成:

package my.package.name;

class MyClass {
    // First description
    private String first;

    // Second description
    private String second;
}

我试图这样开始:

xquery version "1.0";

"package "+$doc/@package
"class "+$doc/@classname
{
for $property in $doc//property
    return {
        "private String "+$property/name::text()
    }
}

语法显然不正确,我想知道它是否可行。谢谢!

4

2 回答 2

1

细节取决于您的查询处理器。应该可以将查询结果作为字符串返回,也可以使用 XSL 中的文本序列化方法;但是您调用它的方式因一个查询处理器而异。(两种方式的区别在于,文本序列化方式会自动将查询结果中的任何内容转成字符串,然后将字符串拼接起来)。

以下是如何以返回单个字符串的查询的形式执行此操作:

declare variable $nl "= '&#10;';
concat(
  "package ", $doc/@package, $nl,
  "class ", $doc/@classname, $nl,
  string-join(
    (for $property in $doc//property
     return {
        concat("private String ", $property/name)
     }), $nl)
)
于 2012-07-09T13:17:44.893 回答
1

查询:

declare function xf:XML2Java($configuration as element(configuration))
    as xs:string {
    let $package := string($configuration/@package)
    let $newline := "&#13;"
       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," }")     
};

输入:

<configuration package="com.test">
    <property>
        <name>Test</name>
        <value>somevalue</value>
        <description>This is test variable</description>
    </property>
</configuration>

输出:

com.test
class MyClass{
//This is test variable
private String Test;
 }

这是在 WebLogic 研讨会 XQuery 设计器中完成的。

于 2012-07-09T13:22:16.803 回答