节点查询(xpath使用)

Node searchOneNodeByXpath(String strXpath) {// 只取真正的节点
		if (myDoc == null)
			return null;

		String sPrgId = "searchOneNodeByXpath : ";

		try {
			myDoc.normalize();
			XPathFactory factory = XPathFactory.newInstance();
			XPath xpath = factory.newXPath();

			XPathExpression expr = null;
			// strXpath=/ROOT/MSG/table1[a1='logrrn1']或者

strXpath=/ROOT/MSG/table1或者strXpath=/ROOT/MSG/table1[@id='1001']
			expr = xpath.compile(strXpath);

			Object result = expr.evaluate(myDoc, 

XPathConstants.NODESET);
			NodeList nodes = (NodeList) result;
			if (nodes.getLength() != 1) {
				System.out.println(sPrgId + "num of [" + strXpath + 

"]="
						+ nodes.getLength() + "!=1.");
				return null;
			}
			if (nodes.item(0).getNodeType() != Node.ELEMENT_NODE) {
				System.out.println(sPrgId + "[" + strXpath
						+ "]node type != ELEMENT.");
				return null;
			}
			return nodes.item(0);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
 

你可能感兴趣的:(xpath)