Add files to the database
Is it possible to add Document objects (org.w3c.dom) directly to the database without using TransformerFactory to convert it first to string?
And what if you have a File object?
Hi Raymond,
Here are some examples using the BaseX XQJ API if that helps.
// ----------------------------------------------------
// Inserting a DOM Document item
// ----------------------------------------------------
import javax.xml.xquery.*;
import javax.xml.namespace.QName;
import net.xqj.basex.BaseXXQDataSource;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import java.io.*;import com.xqj2.*;
public class Test
{
public static final Document getDocument() throws Exception
{
return DocumentBuilderFactory.newInstance().newDocumentBuilder().
parse(new InputSource(new StringReader("<e>Hello World</e>")));
};
public static void main(String[] args) throws Exception
{
XQDataSource xqs = new BaseXXQDataSource();
xqs.setProperty("serverName", "localhost");
xqs.setProperty("port", "1984");
xqs.setProperty("databaseName", "TEST"); // DATABASE NAME: TEST
XQConnection2 conn = (XQConnection2)xqs.getConnection("admin", "admin");Document doc = getDocument();
conn.insertItem( "my-document-uri.xml", conn.createItemFromNode(doc, null), null );
XQPreparedExpression px = // have to state DATEBASE NAME, in URI: conn.prepareExpression("fn:doc('TEST/my-document-uri.xml')");
XQResultSequence rs = px.executeQuery();
System.out.println(rs.getSequenceAsString(null));
conn.close();
}
}
// ----------------------------------------------------
// ----------------------------------------------------
// Inserting an XML Document from a File object
// ----------------------------------------------------
import javax.xml.xquery.*;
import javax.xml.namespace.QName;
import net.xqj.basex.BaseXXQDataSource;
import java.io.*;import com.xqj2.*;
public class Test
{
public static void main(String[] args) throws Exception
{
XQDataSource xqs = new BaseXXQDataSource();
xqs.setProperty("serverName", "localhost");
xqs.setProperty("port", "1984");
xqs.setProperty("databaseName", "TEST"); // DATABASE NAME: TEST
XQConnection2 conn = (XQConnection2)xqs.getConnection("admin", "admin");conn.insertItem( "test.xml", conn.createItemFromDocument( new FileInputStream(new File("test.xml")), null, null ), null );
XQPreparedExpression px = // have to state DATEBASE NAME, in URI: conn.prepareExpression("fn:doc('TEST/test.xml')");
XQResultSequence rs = px.executeQuery();
System.out.println(rs.getSequenceAsString(null));
conn.close();
}
}
// ----------------------------------------------------Quoted text · Raymond Meester · 6 lines
> Is it possible to add Document objects (org.w3c.dom) directly to the > database without using TransformerFactory to convert it first to > string? > > And what if you have a File object? >
Written for BaseX 7.3. BaseX may have changed since: please check the current documentation.