2012-07-09 32 views
1

我想使用XQuery從我的XML文檔生成Java源代碼,例如:XQuery - 是否可以生成非XML文檔?

<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() 
    } 
} 

語法顯然不正確,我不知道它是否可行。謝謝!

回答

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) 
) 
1

的XQuery:

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 Workshop XQuery設計器中做了這個。

相關問題