Wednesday, November 5, 2014

XPath vs XQuery

XPath vs XQuery XPath and XQuery are similar in some ways. XPath is even an integral part of XQuery. Both languages allow you to select bits of data from an XML document or an XML document store.

XPath
XPath is a domain-specific language (DSL) that is quickly becoming an important part of other more general-purpose languages. Programming languages are incorporating XPath through modules and classes, and in some cases directly into the languages' syntax. This is similar to what happened with regular expressions some time ago. XPath is popular because of the considerable amount of time and effort that the language can save a developer when extracting specific bits of data from an XML document.

XQuery
Because XQuery supports XPath natively, as part of XQuery's syntax, XQuery clearly can do everything that XPath can do. XQuery uses a simple syntax that is a mix of XML, XPath, comments, functions, and a special expression syntax to tie it all together. XQuery code consists entirely of expressions with no statements. All values are sequences and simplicity is important to the language. So both of the expressions Hi and 2 * 2 are valid XQuery code that will execute without any prelude or modification. XQuery is a high-level, strongly-typed, functional language (free of side-effects) that is ideal to express a query to obtain data both from an XML document and a large XML document repository. In this last respect, it is much like SQL. But XQuery additionally provides for expressing an arbitrary transformation of the result set. Much like the use of XPath can be rewarding when you want to retrieve some data from an XML document, the use of XQuery can be quite rewarding when you want to retrieve and transform data from a large repository of XML documents.

Summary
XPath is a mature DSL that should be your first choice to get to a piece of data that is buried deep in an XML document or repository. But, XPath was not designed to handle many kinds of problems. As you saw in this article, XQuery extends XPath vastly, emerging as the tool of choice when you have complex data selection requirements or you need to return results that are sorted, specially formatted, or otherwise transformed.