Saturday, January 16, 2010

Embedding XQuery in Java

XQuery is a very powerful language. It can be very useful when you want to do some XML processing in Java.
Let's say you want to create an XML document based on some other XML data. Given something like this:
<employees>
  <employee>
    <name>Fred Jones</name>
    <address location="home">
      <street>900 Aurora Ave.</street>
      <city>Seattle</city>
      <state>WA</state>
      <zip>98115</zip>
    </address>
    <address location="work">
      <street>2011 152nd Avenue NE</street>
      <city>Redmond</city>
      <state>WA</state>
      <zip>98052</zip>
    </address>
    <phone location="work">(425)555-5665</phone>
    <phone location="home">(206)555-5555</phone>
    <phone location="mobile">(206)555-4321</phone>
  </employee>
 </employees>

You want to produce employees' names:
<names>
  <name>Fred Jones</name>
</names>

In XQuery it's just as easy as:
<names>
  {for $name in employees/employee/name/text() return <name>{$name}</name>}
</names>

The most interesting advantage for XQuery over various other methods for generating XML is that XQuery operates natively on XML.
There are tools like JaxB, XmlBeans, which enable strongly typed XML building directly from Java code. But using such approach often requires a lot of Java code to be written, which is not really necessary.
There is also a possibility to use XPath. However it's an inferior solution to XQuery, because XPath doesn't provide a way for building XML documents. It's designed only for nodes selection. On the other hand, XQuery extends XPath, so it supports every construct that XPath does.
Another way to do such processing in Java is to use XSLT. It's the closest approach to XQuery. But the problem with XSLT is that it has its language constructs, like 'for' expressed as XML elements. This makes writing XSLT code much more difficult that XQuery.
XQuery can be seen as a native template language for XML processing.
So the question is: how to evaluate XQuery expressions the best way from Java?
There are some Open Source implementations of XQuery for Java. One of them is inside XmlBeans. However in my opinion the best way is to use Saxon. It's the most mature project for XQuery processing and it's targetted directly for doing that.
However Saxon might be a bit difficult to use directly. At least digging a few interesting features from it took me some time.
So I decided to write a simple class for interfacing Saxon and to provide a few interesting examples of how to use it. That's how xquery4j was born. You can download it from github http://github.com/rafalrusin/xquery4j.
In xquery4j, you can execute XQuery expressions from Java in a simple way:
XQueryEvaluator evaluator = new XQueryEvaluator();
Long result = (Long) evaluator.evaluateExpression("5+5", null).get(0);
Assert.assertEquals(new Long(10), result);

It's possible to bind variables from Java objects, the easy way:
evaluator.bindVariable(QName.valueOf("myVar"), 123);

Sometimes it's also useful to declare Java methods and bind them for XQuery expressions. This is also very simple to do with xquery4j:
public static class MyFunctions {
        public static String myHello(String arg) {
            TestEvaluator te = (TestEvaluator) XQueryEvaluator.contextObjectTL.get();
            te.id++;
            return "hello(" + arg + te.id + ")";
        }
    }

    XQueryEvaluator evaluator = new XQueryEvaluator();
    evaluator.setContextObject(this);
    evaluator.declareJavaClass("http://my.org/employees", MyFunctions.class);
}

This code sets a context object to 'this' and binds all static methods from MyFunctions class to XQuery expressions. So during myHello execution from XQuery, you can easily operate on Java variables from bound context - 'id' in this case.
Here's a way of invoking such bound myHello method from XQuery:
declare namespace my = 'http://my.org/employees'; my:myHello("hello")

xquery4j code contains unit tests, which include examples above.
You can run them by:
mvn package

Feel free to give some feedback on using it.

101 comments:

  1. Your website is amazing. It has a lot of informative stuff. I have become your fan. I will tell my friends about your website. I praise your work. Keep it up.
    thesis research paper

    ReplyDelete
  2. I would like to say that your post is wonderful. We can learn many things from it. You have done a good work. Thanks for posting.
    writing acknowledgements for dissertation

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking. Ruby on Rails Online Training

    ReplyDelete
  5. Get Mutual Fund Investment Schemes by Mutual Fund Wala and know about the best investment platform for you, to get profit.
    Mutual Fund Advisor

    ReplyDelete
  6. Awesome information, visit our page lifestyle magazine to get the best fashion and lifestyle magazines.
    Lifestyle Magazine India

    ReplyDelete
  7. Thanks for your efforts for this blog. Visit Kalakutir Pvt Ltd for Caution & Indication Signages and Warehouse Zebra Painting.
    Warehouse Zebra Painting

    ReplyDelete
  8. Nice post. Thank you to provide us this useful information.
    Bane Coat

    ReplyDelete
  9. Really Impressive, keep it up for more updates. OGEN Infosystem provides responsive web design and seo services at an affordable price.
    SEO Services in Delhi

    ReplyDelete
  10. I found your Blog post which i like it see our the purpose is to share the related Movies, Gaming, Casual,Faux Leather Jackets, Coats And Vests available Jughead Plaid Jacket

    ReplyDelete
  11. 1xbet ได้ทำการก่อตั้งขึ้นในปี 2007 และใช้เวลาภายในไม่กี่ปีเราได้ขึ้นเป็นที่ 1 ในบริษัทรับเดิมพันกีฬาออนไลน์ชั้นนำของโลก.

    ReplyDelete
  12. There are many articles, many different topics on many websites, and this is one of the best posts I have ever seen. Thank you for sharing this post with us. If you want to get an eCommerce web app know more about Magento extensions development.

    ReplyDelete
  13. over the internet, you have posted valuable
    Download Roblox Mod Apk

    ReplyDelete
  14. Programming is what I like the most! That's why the choice of being the writers whose specialization is IT and software technologies, I can produce any kind of paper for my clients, share important gre writing guide after which you may write some of your academic papers by your own.

    ReplyDelete
  15. เราคือทีมพัฒนาเว็บไซต์ ดูหนังออนไลน์ 037 HD ที่เปิดให้บริการ ดูหนังออนไลน์ ฟรี พากย์ไทย เต็มเรื่อง ที่มีหนังให้รับชมทุกประเภท ไม่ว่าจะเป็น หนังไทย หนังฝรั่ง หนัง Netflix และซีรีย์ต่างๆ ที่มีให้เลือกชมมากกว่า 3000 เรื่อง ลื่นไหล ไม่มีกระตุก พร้อมให้บริการ ฟรี 24 ชั่วโมง

    ReplyDelete
  16. assignments that score maximum grades.
    digitechtricks

    ReplyDelete
  17. Hi admin, This is a one of the best article website. Really I am very happy after read this topic release. So please keep your great work and Thankyou so much for sharing this very useful and so outstanding information with us. Australia Assignment Help - Assignment Help Adelaide - Assignment Help - Assignment Help Brisbane

    ReplyDelete
  18. Very nice blog content with superb information provided by your many others topics posts, here I would like to thank you so much guys for sharing such a fantastic niche update. i am going to share it with my mates through social media because every person need like this subject information and i am sure that its very help to everyone. web designing assignment help - pascal assignment help - international finance assignment help - minitab assignment help

    ReplyDelete
  19. Howdy I'm a particular Assistance on the off chance that you dealing with any issue concerning any thing, antivirus so you get in get-together with us:-
    netgear router setup password
    mywifiext local

    ReplyDelete
  20. Fantastic blog i have never ever read this type of amazing information.
    Clint Eastwood Vest

    ReplyDelete
  21. It's a really great and useful piece of information. Thanks, and please keep up the rewarding work. Venom Varsity Jacket

    ReplyDelete

  22. When you feel the need for Assignment Help first you should check the testimonial of the websites that are available on the internet. There are plenty of services in the USA, which make fake promises to the students for providing a good service but many of them get failed.

    ReplyDelete
  23. We are the best Web design company in pune which can provide you the world class website design and development service. Connect with us to get the best quality service at low cost.

    ReplyDelete
  24. Thanks for sharing this amazing blog with some unique information keep it up. Here is gmg transport coupon code

    ReplyDelete
  25. To get help with Law Assignment Help , you need to submit the work details. The services provided by us are highly affordable and fit to your budget. Moreover, by having the online business law assignment help, you no longer need to worry about deadlines. You get your work done before the deadline to evaluate the work to make final adjustments.


    ReplyDelete
  26. atuoyo post utme past questions downloadI'm so much in love with this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thanks for sharing.

    ReplyDelete
  27. Great write up. I have never seen such a masterpiece formulated with precision, accuracy and much-needed information. Thanks for sharing. But you want to access ample datasets for your assignments, take free assistance from SourceEssay Essay Typer.

    ReplyDelete
  28. I could not have asked for better !!! my Subscribers will love them !!!Love my hoodie sherazfabrics, nice soft material, the print is top notch.

    ReplyDelete
  29. Great write up. I have never seen such a masterpiece formulated with precision, accuracy and much-needed information. Thanks for sharing.
    palm angels clothing

    ReplyDelete
  30. Get the best digital marketing service by connecting with SEO Company in dadar. PromoteDial can be the right choice for you.

    ReplyDelete
  31. Assure India is able to provide you the best smartphone insurance at an affordable price. Connect with us for more information.

    ReplyDelete
  32. Goal tide is the best IAS coaching center, we have trained, qualified, and experienced teacher who passed toughest exam of UPSC. Join with us and come true your dreams.
    Best UPSC Prelims Daily Current Affairs

    ReplyDelete
  33. De var så søde hele vejen igennem. Og de gik samtidig meget op i hygiejnen. Så inden vi blev sluppet løs til take away Birkerød at hente en salat i salatbaren, blev vi nøje instrueret i at vi skulle bruge sprit og handsker, at vi ikke måtte bruge handskerne mere end én gang og at vi skulle tage nye skåle, hvis vi ville hente flere gange. Vi var målløse og positivt overraskede. Det er første gang vi har oplevet så nøje instruktion på en restaurant her i Covid-19 tiden.

    ReplyDelete
  34. Great nice information, keep writing. If there is any student need for Online Assignment Help Ireland at very pocket-friendly cost then this message for you. I am providing assignment services for 7 years and we have a super expert team especially our experts from Ireland. If you need then reach out to us. For more information right visit my website.

    ReplyDelete
  35. Online assignment help in Ireland is a service that is provided to students who cannot manage to finish their assignment on time. assignment is usually given with deadlines attached to them. In countries like the Ireland, students often work and study simultaneously which can be stressful and quite difficult for them to manage at the same time.

    ReplyDelete
  36. Many students have difficulty completing assignments at the last minute. They don't want to take a chance on their grades. They should therefore take assignment assistance from experienced Assignment help Australia. As an experienced assignment writer, I can help you with your assignment.

    ReplyDelete
  37. Connect with the best website design & development service provider that name is CSS Founder Pvt Ltd. We can be the right choice for you. Website design company in Dubai

    ReplyDelete
  38. Nice post keep up.What is the difference between affect and effect read it. Affect is a verb and effect is a noun. It seems so near by it's meaning but both have their own meaning. Wants to know Raven Techniques ,visit on blog explore more thing.

    ReplyDelete
  39. Do you want Work permit in poland? If yes then connect with Steadfast services that is located in United Arab Emirates.

    ReplyDelete
  40. Our expert Online Minitab assignment consultants provide you with high-quality and trustworthy Minitab Assignment Help . Analysis of the data, sampling, are just a number of the topics we cover in our assignment help. Minitab is a program tool that helps students with statistical studies such as logistic, measurement, grouped, and cost estimates.

    ReplyDelete
  41. Students feel stressed in writing assignments connected to many areas as a result of the growth of education in universities and other academic institutions. The role of online assignment help services, which are knowledgeable enough to give you with high-quality assignments that will help you improve your grades.
    mathematics assignment help
    nursing assignment help
    chemistry assignment help
    economics assignment help

    ReplyDelete

  42. Selvom det var lørdag aften og der var meget travlt, kom personalet ofte forbi og spurgte ind indisk mad amager til om alt var som det skulle være. Ventetiden på maden føltes ikke lang, da vi kunne starte med forret og salatbaren. Alt i alt var det en rigtig god oplevelse og kan helt klart anbefales. Vi kommer igen meget snart.

    ReplyDelete
  43. Hey, this is San. I am an essay writing expert with 9 years of experience in writing. I have assisted people with hooks for essays and writing essays of all niches. If you are struggling with an essay, then reach out to me. I am always ready to help!

    ReplyDelete
  44. Every company also has its own unique website development process but there is a certain process, we have elaborated it to develop and rank your website. Contact for more information
    Web design company Cambridge

    ReplyDelete
  45. If you have no time Use Assignment Help Australia Services for assistance. Writing assignments is difficult, and mostly people find it exhausting. Connect with our assignment helper

    ReplyDelete
  46. If you want to grow your business through a website, then CSS Founder would be a good choice for you? contact us to connect with CSS Founder. CSS Founder is the best website design company
    Web design company Sundee

    ReplyDelete
  47. Pormotedial is the best SEO company in Dammam, we are the leading company in the SEO field, We have a skilled team that provides you with better result and optimize your website.

    ReplyDelete
  48. I’ve worked with Great Assignment team & I’ve experienced in the field of Chemistry with Ph.D. , master's degrees & 6 years work experienced. We believe in Quality and Scoring Content assignment in the field of Organic , Inorganic , Analytical , Biological Chemistry. So, I & our team have providing Comprehensive support from online CHEMISTRY ASSIGNMENT HELP . help enables students to get great scores with impressive assignments.

    ReplyDelete
  49. Very nice blog and information you have shared. Connect with Al mumtazt tents if you are looking to making your party more impressive. We are the best provider of tents in Dubai. Car Parking Shades

    ReplyDelete
  50. Hi are using Wordpress for your site platform? I’m new to the blog world but I’m trying to get started and create my own. Do you need any coding expertise to make your own blog? Any help would be greatly appreciated!금정출장마사지
    연제출장마사지
    수영출장마사지
    사상출장마사지
    수성출장마사지
    달서출장마사지
    미추홀출장마사지

    ReplyDelete
  51. On this website, you can find professionally created tips on how to write a movie essay and other similar papers. Hurr on to get quality support and earn bonuses.

    ReplyDelete
  52. Thanks for providing the best and nice information about it. GP in Dublin

    ReplyDelete
  53. This has really made me think and I hope to read more.Pelle Pelle Chi-Town White Jacket

    ReplyDelete
  54. his is really nice, thanks again for this wonderful and Freight Forwarding valuable information sharing with us.

    ReplyDelete
  55. This comment has been removed by the author.

    ReplyDelete
  56. They can be worn for both casual and formal occasions and can be dressed up or down depending on the occasion. Google

    ReplyDelete
  57. One of the main reasons behind global product sourcing is to save money. Because the global market is so competitive china sourcing blog

    ReplyDelete
  58. place is proving the beauty of Australia. Australia is the most beneficial country for visitincI look up to the valuable selective information you eddie stranger things jacket

    ReplyDelete
  59. I'm super excited for giving me the privilege to learn through your blog. Its a nice time with you today. Thanks alot, I hope to always come around for new updates. ondo city polytechnic form out

    ReplyDelete
  60. We became a life savior for the UK students with our assignment help Glasgow. Connect with us to get the assignment helper in Glasgow. If you want to get the best assignment help in Glasgow at a reasonable price with quality content, get in touch with our experts with different skills today itself. Being the most popular online assignment writing service provider you get the best subject matter experts with a wealth of expertise in their field. Our professional writers who can handle multiple projects in one go without compromising quality.

    ReplyDelete
  61. تعتمد شركات شيش حصير في مصر في تركيب شيش الحصيرة باستخدام المشابك:

    يمكن استخدام هذه الطريقة في حالة عدم توفر الأشرطة لتركيب الحصيرة. ويمكن استخدام المشابك البسيطة لتثبيت الحصيرة بشكل جيد. ويتم ذلك عن طريق وضع المشابك في الغرزة بين الغطاء والقاعدة

    ReplyDelete
  62. تعد الشرايين الطرفية واحدة من الأجزاء الرئيسية في النظام الدوراني، حيث تمد الأطراف السفلية والعلوية بالدم والأوكسجين والمواد الغذائية الأخرى التي يحتاجها الجسم. ومن المشاكل الشائعة التي تؤثر على هذا النظام هي انسداد الشرايين الطرفية، والتي تحدث عندما تنسد الشرايين التي تمد الأطراف بالدم. لذلك من الافضل التعامل مع احسن دكتور اوعية دموية الا وهو الدكتور محمود ناصر.

    ReplyDelete
  63. Pretty! This has been an incredibly wonderful article. Many thanks for supplying this info. Dwayne Johnson Fast X Blazer

    ReplyDelete
  64. Thank you for sharing such an insightful blog post! "Get expert Business Assignment Help for guaranteed success. Our professional team provides comprehensive assistance and delivers high-quality solutions tailored to your specific needs. Achieve exceptional grades and excel in your business studies with our reliable and timely assignment support. Contact us now!"

    ReplyDelete
  65. We're grateful for your sharing of this informative blog. Should you find yourself in need of an assignment help, don't worry; your journey has come to an end. Our team of devoted experts is here 24/7 to help you excel in your pursuits. They are always prepared to assist with any assignment-related inquiries. Feel free to reach out to us.

    ReplyDelete
  66. Brian's Club is just one example of the countless underground forums and Briansclub marketplaces where

    ReplyDelete
  67. I really amazed to read this blog post. It is so unique and informative Christmas Sale

    ReplyDelete
  68. Soda ash prices have historically exhibited volatility, influenced by factors like supply-demand dynamics, production costs, and global economic trends. Prices for soda ash, a key raw material in various industries including glass, detergents, and chemicals, tend to fluctuate based on shifts in production capacities, energy costs, and environmental regulations impacting the manufacturing process. In recent years, market variations have been observed due to factors such as changes in raw material costs, energy prices, and trade dynamics, affecting the overall pricing of soda ash on both regional and international scales.

    ReplyDelete
  69. Walking into this salon feels like stepping into a high-end spa retreat. The interior design is a harmonious blend of luxury and practicality, with every detail carefully curated to enhance the overall experience. It's no wonder clients rave not only about the exceptional service but also the beautiful ambiance. salon interior design

    ReplyDelete

  70. توجد العديد من الأنواع المتقدمة من ماكينات التعبئة والتغليف التي تلبي احتياجات مختلفة في مجال التعبئة والتغليف. إليك بعض الأنواع الحديثة التي تحظى بشعبية:

    ماكينات تعبئة مياه معدنية بالفراغ (Vacuum Packaging Machines): تقوم هذه الماكينات بسحب الهواء من العبوة لتحقيق فراغ داخلي، مما يساعد في حفظ الطعام لفترة أطول والحفاظ على جودته.
    ماكينات التعبئة بالغاز الواقي (Modified Atmosphere Packaging Machines - MAP): تستخدم هذه الماكينات خليطًا من الغازات لخلق بيئة محمية داخل العبوة، مما يساعد في تمديد عمر الصلاحية للمنتجات الطازجة.

    ReplyDelete
  71. يتميز Egypt in show furniture classic بتصاميمه الفريدة والأنيقة، والتي تعكس الأناقة والفخامة الفرنسية التقليدية وتقدم معارض الأثاث الفرنسي في مصر خدمة عملاء ممتازة، بما في ذلك المشورة الفنية والمساعدة في اختيار الأثاث المناسب وفقًا لاحتياجات العميل وأذواقه و تقدم معظم معارض الأثاث الفرنسي في مصر تخفيضات وعروض خاصة بشكل منتظم، مما يساعد العملاء على الحصول على قطع الأثاث بأسعار مخفضة وميزانيات معقولة.

    ReplyDelete
  72. ماكينة تعبئة وتغليف لب هي جهاز يستخدم لتعبئة وتغليف منتجات اللب، مثل عصير الفواكه أو الحليب. تقوم هذه الماكينات بملء السوائل في عبوات مثل عبوات الزجاج أو الورق ومن ثم تغليفها بإحكام لضمان سلامة المنتج وحفظ جودته.

    ReplyDelete
  73. This is the real website for men who love GAP Hoodies. Our store has the newest sweatshirts and tracksuits.
    gap hoodie

    ReplyDelete
  74. Your expertise shines through in every article. Thank you! briansclub.cm
    briansclub.cm

    ReplyDelete
  75. Escalators reduce the physical strain associated with climbing stairs, which is particularly beneficial for people carrying heavy items or those with health issues. Elevator cabin factories in Egypt offer a more stable option for those who might have difficulty maintaining balance on stairs.

    ReplyDelete
  76. Your post is incredibly informative and well-written. It’s clear that you have a deep understanding of the topic vault market

    ReplyDelete
  77. "Thanks for sharing this. I’m definitely going to try [suggestion]!"

    ReplyDelete
  78. This article was a standout for me. Your fresh take on the subject and the way you articulated your thoughts made it a truly memorable read. I’m grateful for the new perspective you provided and can’t wait to see what you’ll write about next.
    brians club

    ReplyDelete
  79. Each time I read your blog, I feel like I’m gaining a deeper understanding of the world. This post was especially eye-opening—thank you for sharing your wisdom.
    briansclub cm

    ReplyDelete
  80. I’m thrilled with the quality of my reconditioned Range Rover engine. It’s like getting a new engine at a fraction of the price! reconditioned range rover engines

    ReplyDelete
  81. I can’t get enough of Pull Stussy’s designs. Their pieces are always on-trend and versatile for any casual outfit. Pull Stussy

    ReplyDelete
  82. The quality of these Hellstar shorts is incredible. Worth every penny.

    ReplyDelete
  83. I appreciate the care and thoughtfulness you put into your writing. This was another excellent post!
    briansclub.cm

    ReplyDelete
  84. "I’m impressed with your expertise on this subject. Keep it up!

    ReplyDelete
  85. Frontier JFK Terminal is located in Terminal 5 at John F. Kennedy International Airport in New York. This terminal serves as the main hub for Frontier Airlines, offering passengers a range of budget-friendly travel options. With a modern and efficient layout, the Frontier JFK Terminal features various amenities including food courts, retail shops, and comfortable seating areas. It provides a streamlined, no-frills experience, in line with Frontier's commitment to low-cost flying. Additionally, the terminal is well-connected to JFK's transportation system, offering easy access to the AirTrain, taxis, and other ground transportation options.
    frontier jfk terminal
    delta terminal las vegas
    condor rollstuhlservice
    What Terminal is Delta Airlines at JFK

    ReplyDelete