Pukka
Pukka

Reputation: 11

Error when retrieving from my xml document using xquery

I am trying to retrieve the authors from my XML documents but some of the authors have apostrophe's in their names so the results throw an error.

Input:

<dblp>
    <book mdate="2002-01-03" key="books/aw/CeriF97">
        <author>Stefano Ceri</author>
        <author>Piero Fraternali</author>
        <title>Designing Database Applications with Objects and Rules: The IDEA Methodology</title>
        <publisher href="db/publishers/aw.html">Addison-Wesley</publisher>
        <year>1997</year>
        <isbn>0-201-40369-2</isbn>
    </book>
</dblp>

Java/XQuery Code:

public ArrayList<String> getArrayListOfAuthors(){

    String query = "for $x in fn:distinct-values(doc(\"" +xml_file_name+ "\")//author) " +
                    "order by $x "+
                    "return $x";

    System.out.println("XQuery query:"+query);
    ArrayList<String> myList = new ArrayList<String>();
    try{
        XQDataSource ds = new SaxonXQDataSource();
        XQConnection conn = ds.getConnection();
        XQExpression exp = conn.createExpression();

        XQSequence seq = exp.executeQuery(query);
        int i = 1;

        while (seq.next()) {
            i++;
            //System.out.println(seq.getAtomicValue());
                            myList.add(seq.getAtomicValue());
        }
        //System.out.println("\n== Total number of authors is "+i+" ==");

        seq.close();

    } catch (XQException err) {
    System.out.println("Failed as expected: " + err.getMessage());
    }
              return myList;
}

Error Message:

XPST0003 XQuery syntax error near #...e $y/author = 'Kieran O'Neill'#:
    Unmatched quote in expression
Error on line 1 column 109 

Upvotes: 1

Views: 245

Answers (1)

Michael Kay
Michael Kay

Reputation: 163322

The error message strongly suggests that you are constructing a query by string concatenation, perhaps by processing the list of authors obtained from the query you have shown us. (Look for a query containing $y, which isn't the one in your sample).

Then change it so that instead of constructing a query using concatenation like this:

query = "//author[@name="' + name + "']"

you construct the query to contain a parameter:

query = "declare variable $name external; //author[@name=$name]"

and execute this supplying the value of $name as a run-time parameter. There are several benefits apart from avoiding the problem of names containing apostrophes: you avoid the security problems of injection attacks, and you get a performance benefit because you can compile the query once and use it repeatedly.

Upvotes: 3

Related Questions