You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中运行XQuery查询?已知xml2包支持XPath查询

Running XQuery in R

Great question! While xml2 is the go-to package for XPath queries in R, there are reliable ways to execute XQuery directly within your R workflow. Let’s break down the most practical options:

1. RSaxon Package

This package wraps the Saxon XSLT and XQuery processor—an industry-standard tool for advanced XML processing—and supports XQuery 3.1. It’s the most robust choice for complex XQuery work in R.

Setup & Quick Example

First, install the package (note: it requires Java to be installed and configured on your system):

install.packages("RSaxon")
library(RSaxon)

You can run XQuery against XML documents loaded from files or strings. Here’s a self-contained example:

# Define a sample XML string
xml_str <- '<library>
  <book>
    <title>XQuery in Practice</title>
    <price>29.99</price>
  </book>
  <book>
    <title>R for Data Science</title>
    <price>24.99</price>
  </book>
  <book>
    <title>Beginner XML</title>
    <price>14.99</price>
  </book>
</library>'

# Parse the XML into an xml2 document
xml_doc <- xml2::read_xml(xml_str)

# Write your XQuery expression (here, fetch titles of books over $20)
xquery_expr <- 'for $book in //book where $book/price > 20 return $book/title/text()'

# Execute the query
query_results <- saxon_xquery(xml_doc, xquery_expr)

# View the results
print(query_results)

RSaxon supports advanced XQuery features like custom functions, variables, and module imports, making it suitable for production-level XML processing.

2. Command-Line Tools via system()

If you prefer avoiding Java dependencies, you can use R’s system() function to call external XQuery command-line tools (like Saxon-HE or BaseX) directly. This approach requires you to have the tool installed separately, but it’s flexible for simple use cases:

# Run an XQuery file against an XML document and read results into R
query_output <- system("java -jar saxon-he-12.4.jar -s:my_data.xml -q:my_query.xq", intern = TRUE)

# Print the results
cat(query_output, sep = "\n")

Quick Tips

  • For RSaxon, if you run into Java-related issues, verify your Java setup with java::jinit() (from the rJava package, which RSaxon depends on).
  • XQuery 3.1 adds powerful features like higher-order functions and string manipulation—RSaxon lets you leverage all of these in R.

内容的提问来源于stack exchange,提问作者Massimo Franceschet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:23:03