我正在尝试使用Java BaseX XQJ API数据插入XML 文件。代码如下
(省略导入):
public class BaseXTest {
public static void main(String[] args) throws Exception {
// obtain an XQDataSource instance
XQDataSource ds = new BaseXXQDataSource();
ds.setProperty("serverName", "localhost");
ds.setProperty("port", "1984");
ds.setProperty("user", "admin");
ds.setProperty("password", "admin");
XQConnection xqc = ds.getConnection();
XQExpression xqe = xqc.createExpression();
xqe.executeCommand("CREATE DB myTestDB");
ds.setProperty("databaseName", "myTestDB");
File myTestDbDataFile = new File("PATH_TO_MY_XML_FILE");
XQConnection2 xqc2 = (XQConnection2) ds.getConnection();
XQItem xqItem = xqc2.createItemFromDocument(new FileInputStream(myTestDbDataFile), null, null);
xqc2.insertItem(myTestDbDataFile.getName(), xqItem, null);
//this query works
// XQResultSequence rs = xqe
// .executeQuery("for $i in (1 to 10) return $i");
//this query works too
// XQResultSequence rs =
// xqe.executeQuery("doc('PATH_TO_MY_XML_FILE')/myTestDbRootNode");
//this query works NOT
XQResultSequence rs = xqe.executeQuery("insert node 'abcdefg' into doc('PATH_TO_MY_XML_FILE')/myTestDbRootNode");
rs.writeSequence(System.out, null);
xqc.close();
}
}
上面的代码抛出这个异常(符合语句' rs.writeSequence(System.out, null); '):
Exception in thread "main" javax.xml.xquery.XQException:
XQJFOS021 - FORWARD_ONLY_SEQUENCE: Cursor is not positioned on an XQItem.
at XmlTestMain.main(XmlTestMain.java:118)
为什么会这样和如何向数据库发出有效的“插入”指令?
我猜在插入的情况下使用“executeQuery()-方法”有问题,因为它可以处理发出的其他两个指令。