java通过XPATH解析XML

http://www.oschina.net/code/snippet_573074_12408


package testXpath;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.NodeList;

public class TestXpathExample {
	public static void main(String args[]) throws FileNotFoundException, TransformerException, XPathExpressionException{
		TransformerFactory transFact = TransformerFactory.newInstance();
		Transformer transFormer = transFact.newTransformer();
		DOMResult dom = new DOMResult();
		transFormer.transform(new StreamSource(new FileInputStream(new File("test.xml"))), dom);
		
		XPath xpath = XPathFactory.newInstance().newXPath();
		
		@SuppressWarnings("serial")
		Map<String,String> prefix2uri = new HashMap<String,String>(){{
			
			put("foo","http://www.baidu.com");
			put("bar","http://www.google.com");
			
		}};
		
		@SuppressWarnings("serial")
		Map<String,String> uri2prefix = new HashMap<String,String>(){{
			put("http://www.baidu.com","foo");
			put("http://www.google.com","bar");
		}};
		
		
		xpath.setNamespaceContext(new NsSolver(prefix2uri,uri2prefix));
		
		XPathExpression expression = xpath.compile("//player");
		
		NodeList nodeList = (NodeList)expression.evaluate(dom.getNode(),XPathConstants.NODESET);
		
		for(int i = 0; i < nodeList.getLength(); i++){
			System.out.println(nodeList.item(i).getNodeName());
		}
	}
}


你可能感兴趣的:(java通过XPATH解析XML)