如何使用XQuery使用Java中的Saxon输出json

我正在使用XQuery将下面的XML文档转换为JSON,使用Saxon来处理XQuery文件.

<books>
   <book id="book1">
      <author>Book1AuthorSurname, Book1AuthorFirstname</author>
      <title>Book1 Title</title>
      <price>45.00</price>
   </book>
   <book id="book2">
      <author>Book2AuthorSurname, Book2AuthorFirstname</author>
      <title>Book2 Title</title>
      <price>45.00</price>
   </book>
</books>

XQuery本身非常简单

xquery version "3.1";

declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; 
declare namespace map = "http://www.w3.org/2005/xpath-functions/map";

declare option output:method "json";
declare option output:indent "yes";

let $booksXML := doc("books.xml")/books

return array {
  for $book in $booksXML/book
  return map {
   "author": data($book/author),
   "title": data($book/title)
  }
}

并且,如果我从Saxon的命令行运行它,则返回正确

java -cp Saxon-HE-9.8.0-8.jar net.sf.saxon.Query -q:books2json.xqy

 [
   {
    "author":"Book1AuthorSurname, Book1AuthorFirstname",
    "title":"Book1 Title"
   },
   {
    "author":"Book2AuthorSurname, Book2AuthorFirstname",
    "title":"Book2 Title"
   }
 ]

但是使用以下代码段从Java运行它会产生稍微不同的结果

Processor saxon = new Processor(false);
XQueryCompiler compiler = saxon.newXQueryCompiler();
XQueryExecutable exec = compiler.compile(new File("books2json.xqy"));
XQueryEvaluator query = exec.load();
XdmValue result = query.evaluate();
System.out.println(result.toString());

[
    map{"author":"Book1AuthorSurname, Book1AuthorFirstname","title":"Book1 Title"},
    map{"author":"Book2AuthorSurname, Book2AuthorFirstname","title":"Book2 Title"}
]

Java输出中的“map”在我用来读取结果的JSON处理器中给出错误,是否有一个配置选项可以从结果中删除它?

解决方法:

如果你想直接写入System.out或其他任何目的地,那么你可以使用run方法这样做:

    Processor saxon = new Processor(false);
    XQueryCompiler compiler = saxon.newXQueryCompiler();
    XQueryExecutable exec = compiler.compile(new File("query1.xq"));
    XQueryEvaluator query = exec.load(); 

    query.run(saxon.newSerializer(System.out));
    System.out.println();

分别如果你想让一个String在StringWriter上使用一个Serializer:

    StringWriter sw = new StringWriter();
    query.run(saxon.newSerializer(sw));
    String result = sw.toString();
    System.out.println(result);
上一篇:maven 手动加载第三方jar、zip包


下一篇:c# – 从Saxon 9.4he中的嵌入资源加载xml和xslt