使用XQuery和Java将元素插入XML

时间:2012-07-12 00:48:47

标签: xml xquery saxon xquery-update

我需要使用XQuery插入表达式将新元素插入到XML文档中。我使用saxon作为java api。我是XQuery的新手,所以我不确定insert表达式的确切结构。任何人都可以帮助我。

我的XML文件如下所示:

<?xml version="1.0" encoding="ISO-8859-1"?>
<breakfast_menu>
<food>
 <name>Belgian Waffles</name>
 <price>$5.95</price>
 <description>two of our famous Belgian Waffles with plenty of real maple syrup<description>
 <calories>650</calories>
</food>
 </breakfast_menu>

我执行插入的java代码是

public void insert() throws XQException{
    String queryString =
            //"declare variable $docName as xs:string external;"  + sep +
            "variable $stores := doc("+"food.xml"+")/*;"+
            "insert node element food {"+
            "element name { \"brnj\" },"+
            "element price { \"$20\" },"+
            "element description { \"whatever\" },"+
            "element calories { 300 },"+
            "} into $stores;";

 XQPreparedExpression expr = conn.prepareExpression(queryString);
 expr.bindObject(new QName("stores"), "food.xml", null);
 XQResultSequence rs = expr.executeQuery();
}

我得到的错误是查询字符串的语法。 请帮忙。

3 个答案:

答案 0 :(得分:2)

XQJ API不支持XQuery更新。我相信一些供应商已经扩展了XQJ以支持更新,但由于XQJ的许可条件对试图扩展API的任何人施加了死刑,我在Saxon中没有这样做。 (我也没有意识到任何定义此类扩展的举措 - 从开始之日起,XQJ被律师扼杀,原因我从未理解过。)

如果您使用Saxon作为XQuery更新引擎,我建议使用s9api界面。这是一个例子:

   public void run() throws SaxonApiException {
        Processor proc = new Processor(true);
        XQueryCompiler comp = proc.newXQueryCompiler();
        comp.setUpdatingEnabled(true);
        XQueryExecutable exp = comp.compile(
                "for $p in doc('data/books.xml')//PRICE " +
                "return replace value of node $p with $p + 0.05");

        XQueryEvaluator eval = exp.load();
        eval.run();
        for (Iterator<XdmNode> iter = eval.getUpdatedDocuments(); iter.hasNext();) {
            XdmNode root = iter.next();
            URI rootUri = root.getDocumentURI();
            if (rootUri != null && rootUri.getScheme().equals("file")) {
                try {
                    Serializer out = proc.newSerializer(new FileOutputStream(new File(rootUri)));
                    out.setOutputProperty(Serializer.Property.METHOD, "xml");
                    out.setOutputProperty(Serializer.Property.INDENT, "yes");
                    out.setOutputProperty(Serializer.Property.OMIT_XML_DECLARATION, "yes");
                    System.err.println("Rewriting " + rootUri);
                    proc.writeXdmValue(root, out);
                } catch (FileNotFoundException e) {
                    System.err.println("Could not write to file " + rootUri);
                }
            } else {
                System.err.println("Updated document not rewritten: location unknown or not updatable");
            }
        }
    }

大部分复杂性在于将更新的文档写回文件存储 - 当然,这不一定是您想要做的。

请注意,只有Saxon的商业版本才支持XQuery更新。

答案 1 :(得分:1)

BaseX XQJ API支持XQuery Update Facility 1.0和3.0,它允许您更新BaseX数据库中的文档。

您也可以通过MarkLogic XQJ API,Sedna XQJ API和eXist XQJ API更新数据库内文档,但不是通过XQuery Update Facility,因为这些实现还不支持XQUF。

最后也可能最重要的是你的问题,你可能会发现Ryan Grimm的“in-mem-update”库模块非常有用[1]。我当然有过无数次。

你可以

  • 将库模块与任何XQuery处理器+ XQJ
  • 一起使用
  • 对内存中的XML文档执行更新(无需写入磁盘)。
  • 在一个XQuery中对文档执行“多个”更新操作
  • 可以在XQResultSequence中返回更新的内存中文档(非常适合您)。

此外,为了明确说明,XQJ 1.0规范并不禁止供应商支持XQuery更新工具。

摘自规范:

“18.6支持更新和交易

虽然更新功能不是[XQuery]的一部分,但XQJ需要一些 实现将包括一些专有扩展来处理更新功能。“

[1] https://github.com/marklogic/commons/blob/master/memupdate/in-mem-update.xqy

答案 2 :(得分:1)

现在可以。

上传查询:

company: company_id, other company info (such as name) 
department: department_id, company_id (referencing the company record), other department info 
user: user_id, company_id (referencing the company record), other user info
user_departments: user_id, department_id, perhaps information such as user's role in department, or if you want historical data preserved dates assigned to and removed from department

插入/选择查询:

public static void ejecutarConsultaU(String cadenaAConsultar) throws XQException {
    XQExpression consulta;
    consulta = xqc.createExpression();
    System.out.println("Inicio consulta \n");
    System.out.println(cadenaAConsultar);
    System.out.println("fin consulta \n");
    consulta.executeCommand(cadenaAConsultar);}
相关问题