% GETXDOC retrieves an object with given id from the LTPDA
% repository specified by the input database connection. The object is
% converted from its XML text format to an Xdoc. This can then be converted
% into an object using the appropriate object constructor.
%
% Usage: xdoc = getXdoc(conn, id)
%
% Inputs:
%         conn - a database connection object
%         id   - the object id
%
% Outputs:
%         xdoc - an Xdoc representation of the object.
%
% M Hewitson 30-08-07
%
% $Id: getXdoc.m,v 1.2 2009/06/17 11:05:53 ingo Exp $
%
%

function xdoc = getXdoc(conn, id)

  xdoc = '';
  
  try
    results = conn.query(sprintf('select xml from objs where id="%d"', id));
    while results.next
      objTxt = char(results.getString(1));
    end
  catch curs
    error('### Unable to read xml for ID %d. Server returned %s', id, curs.message);
  end

  if ~isempty(objTxt) && ~strcmp(objTxt(:), 'No Data')
    % convert to Java string
    str = java.lang.String(objTxt);
    % open stream on this string
    stream = java.io.StringBufferInputStream(str);
    % make parser
    builder = javax.xml.parsers.DocumentBuilderFactory.newInstance.newDocumentBuilder;

    xdoc = builder.parse(stream);
  else
    xdoc = [];
  end

end

