xquery在java中的应用

/**
 * 执行查询
 * @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 (必须要的)

你可能感兴趣的:(java,xml,xquery)