当前位置: 动力学知识库 > 问答 > 编程问答 >

xquery - How to access files in BaseX without creating a database?

问题描述:

I need to transform some XML files based on a context provided by the -i option of BaseX command line tool:

$ basex --help

BaseX 8.4.2 [Standalone]

Usage: basex [-bcdiIoqrRstuvVwxXz] [input]

[input] XQuery or command file, or query string

-b<pars> Bind external query variables

-c<input> Execute commands from file or string

-d Activate debugging mode

-i<input> Assign file or database to context

-I<input> Assign input string to context

-o<output> Write output to file

-q<expr> Execute XQuery expression

-r<num> Set number of query executions

-R Turn query execution on/off

-s<pars> Set serialization parameter(s)

-t[path] Run tests in file or directory

-u Write updates back to original files

-v/V Show (all) process info

-w Preserve whitespaces from input files

-x Show query plan

-X Show query plan before/after compilation

-z Skip output of results

I don't want to use a database, since I need to create a database explicitly. Could I use basex -i context.xml test.xqy to combine the context with the transformation, and inside the test.xqy file, could I access the context.xml directly using something like doc('context')?

Are there other XQuery processors providing this functionality?

网友答案:

Accessing Files Without Creating a Database

I don't want to use a database, since I need to create a database explicitly. Could I use basex -i context.xml test.xqy to combine the context with the transformation, and inside the test.xqy file, could I access the context.xml directly using something like doc('context')?

For ad-hoc queries, the easiest way is to pass the document in the doc(...) function. In BaseX, the doc(...) function can be used to access databases, local files and even remote URIs, as explained in the Databases/XML Documents chapter of the BaseX documentation. If the name does not match a database name, BaseX will try to open a file with this name instead. You can also provide relative or absolute paths to the doc(...) function.

Actually, this creates an in-memory database representation of the file (which is necessary for reasonable performance, textual XML is not really a good fit for fast evaluation of queries), but this happens transparently (but requires the document to fit in the main memory).

For example, to count the number of elements in the context.xml file stored in the working directory, run

count(doc('context.xml')//*)

Updating Files

I need to transform some XML files[...]

This is also possible on XML files opened this way, but be sure to set the WRITEBACK option, which is also possible using the -u parameter:

-u          Write updates back to original files
分享给朋友:
您可能感兴趣的文章:
随机阅读: