How to setContextItem given a string, not a document

saxon-help
2012-10-18
2012-10-18
  • Oana Ureche
    Oana Ureche
    2012-10-18

    Hi all,

    I am trying to run a query over some XML data using XQuery, Saxon and Java.
    And I would like to read the XML data from a string, not a file. I haven't figure out which classes to use, as many classes implement the Item interface. I tried a few with no luck.. maybe I am not on the right track. Please let me know what is the right way.

    String stringSource = "xml input data";
    
    final Configuration config = new Configuration();
    final StaticQueryContext sqc = config.newStaticQueryContext();
    final XQueryExpression exp = sqc.compileQuery(new FileReader("xquery.file"));
    final DynamicQueryContext dynamicContext = new DynamicQueryContext(config);
    
    dynamicContext.setContextItem(new StringValue("stringSource")); //?????????????????? line that needs to be modified
    final Properties props = new Properties(); 
    //... set propos
    exp.run(dynamicContext, new StreamResult(new File("output.file")), props);
    
     
    • Oana Ureche
      Oana Ureche
      2012-10-18

      I found the answer:

      StringReader reader = new StringReader(aString); 
      dynamicContext.setContextItem(config.buildDocument(new StreamSource(reader)));
      
       
  • Michael Kay
    Michael Kay
    2012-10-18

    You seem to have found a forum that was dormant, but has re-appeared from a long sleep as a result of SourceForge migrating to the new platform. I would recommend using the forums at saxonica.plan.io in preference.

    You are using Saxon's original Query API which is rather messy and "for internal use". For external use I would recommend use of the interfaces in the s9api package.

    What you are doing should work fine, except that you are not setting the SystemID of the Source object; this means that Saxon doesn't know its base URI, which means any attempt to resolve relative URIs from this document will fail.