xquery在java中的应用

2 篇文章 0 订阅

/**
* 执行查询
* @throws FileNotFoundException
*/
public static void select() throws FileNotFoundException {
//文件
String fileString = "src/com/farmer/city.xml";
//CATALOG元素(根元素)下的 CD 元素下的所有 title 元素,并以字母顺序返回 title 元素
// String query = "for $s in //CD/TITLE" +
// " order by $s " +
// "return $s";

// HTML 表现出来
String query = "<ul>" +
"{"+
"for $s in //city/id" +
" order by $s " +
//这个还是带TILTLE标签的 下面一个不带"return <li>{$s}</li>" +
"return <li>{data($s)}</li>" +
"}" +
"</ul>";

// 查询语句
//String query = " for $s in /CATALOG/CD/PRICE" + " return $s";

//并且所选取的 CD 元素下的 price 元素的值必须等于 10.90:
//String query = " for $s in /CATALOG/CD[PRICE=10.90]/PRICE " + " return $s";

//下面这个表达式可选取 CATALOG 元素下的 CD 元素下所有的 TITLE 元素,并且其中的 PRICE 元素的值必须大于 10.90
//String query = " for $s in /CATALOG/CD[PRICE=10.90]/TITLE " + " return $s";

// 生产文档对象
Document document = getDocument(fileString);
Configuration configuration = new Configuration();
StaticQueryContext context = new StaticQueryContext(configuration,
false);
// 查询表达式对象
XQueryExpression expression = null;
try {
expression = context.compileQuery(query);
DynamicQueryContext context2 = new DynamicQueryContext(
configuration);
context2.setContextItem(new DocumentWrapper(document, null,
configuration));

final Properties props = new Properties();
props.setProperty(OutputKeys.METHOD, "xml");
//缩进
props.setProperty(OutputKeys.INDENT, "yes");
// 执行查询,并输出查询结果
expression.run(context2, new StreamResult(System.out), props);
} catch (XPathException e) {
e.printStackTrace();
}

}
/**
* 生产文档对象
*
* @param xml
* 文件名
* @return
*/
public static Document getDocument(String xml) {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
Document document = null;
try {
builder = builderFactory.newDocumentBuilder();
//可以都的是文件流 或 文件地址。即:本地或网络的xml
//document = builder.parse(getStream(xml));
document = builder.parse(xml);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
document.normalize();
return document;
}
public static void main(String[] args) throws Exception {
select();
}


下面是可能会执行出来的结果:

<?xml version="1.0" encoding="UTF-8"?>
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
<li>004</li>
</ul>

参考文档:
http://www.ibm.com/developerworks/cn/xml/x-xjavaxquery/index.html

需要的jar包:saxon9ee.jar (必须要的)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值