@@ -12,20 +12,35 @@ function SparqlXMLResultWriter(sparqlIterator) {
1212SparqlResultWriter . subclass ( SparqlXMLResultWriter ) ;
1313
1414SparqlXMLResultWriter . prototype . _writeHead = function ( variableNames ) {
15- var root = this . _root = xml . element ( { _attr : { xlmns : 'http://www.w3.org/2005/sparql-results#' } } ) ,
16- results = this . _results = xml . element ( { } ) , self = this ;
15+ // Write root element
16+ var self = this ,
17+ root = this . _root = xml . element ( {
18+ _attr : { xlmns : 'http://www.w3.org/2005/sparql-results#' } ,
19+ } ) ;
1720 xml ( { sparql : root } , { stream : true , indent : ' ' , declaration : true } )
1821 . on ( 'data' , function ( chunk ) { self . _push ( chunk + '\n' ) ; } ) ;
19- if ( variableNames . length )
20- root . push ( { head : variableNames . map ( function ( v ) { return { variable : { _attr : { name : v } } } ; } ) } ) ;
21- root . push ( { results : results } ) ;
22+
23+ // Write head element
24+ if ( variableNames . length ) {
25+ root . push ( {
26+ head : variableNames . map ( function ( v ) {
27+ return { variable : { _attr : { name : v } } } ;
28+ } ) ,
29+ } ) ;
30+ }
2231} ;
2332
2433SparqlXMLResultWriter . prototype . _writeBindings = function ( result ) {
34+ // With the first result, write the results element
35+ if ( ! this . _results )
36+ this . _root . push ( { results : this . _results = xml . element ( { } ) } ) ;
37+
2538 // Unbound variables cannot be part of XML
2639 result = _ . omit ( result , function ( value ) {
2740 return value === undefined || value === null ;
2841 } ) ;
42+
43+ // Write the result element
2944 this . _results . push ( {
3045 result : _ . map ( result , function ( value , variable ) {
3146 var xmlValue , lang , type ;
@@ -48,7 +63,12 @@ SparqlXMLResultWriter.prototype._writeBoolean = function (result) {
4863} ;
4964
5065SparqlXMLResultWriter . prototype . _flush = function ( done ) {
51- this . _results . close ( ) ;
66+ // If there were no matches, the results element hasn't been created yet
67+ if ( this . _empty )
68+ this . _root . push ( { results : this . _results = xml . element ( { } ) } ) ;
69+ // There's no results element for ASK queries
70+ if ( this . _results )
71+ this . _results . close ( ) ;
5272 this . _root . close ( ) ;
5373 done ( ) ;
5474} ;
0 commit comments