我正在尝试从我的XML文档中检索作者,但是一些作者的名字中有撇号,因此结果会产生错误。
<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>
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;
}
XPST0003 XQuery syntax error near #...e $y/author = 'Kieran O'Neill'#:
Unmatched quote in expression
Error on line 1 column 109
答案 0 :(得分:3)
错误消息强烈建议您通过字符串连接构建查询,可能是通过处理从您向我们展示的查询中获取的作者列表。 (查找包含$ y的查询,该查询不是样本中的查询)。
然后更改它,以便不使用如下的连接构造查询:
query =“// author [@ name =”'+ name +“']”
构造查询以包含参数:
query =“声明变量$ name external; // author [@ name = $ name]”
并执行此操作,将$ name的值作为运行时参数提供。除了避免包含撇号的名称问题之外,还有几个好处:您可以避免注入攻击的安全问题,并且您可以获得性能优势,因为您可以编译一次查询并重复使用它。