java通过XPATH解析XML

日常开发过程中会遇到很多种xml文件、Source方面的解析

1、基于SOAP协议负载方式传输时服务器会返回Source,此时,需要将Source解析成本地数据:

JAXBContext ctx = JAXBContext.newInstance(User.class);//User对象
Source response = ....			
//1.将Source转化为DOM进行操作,使用Transform对象转换
Transformer tran = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
tran.transform(response, result);
			
//2、处理相应信息(通过xpath处理)
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList)xpath.evaluate("//user", result.getNode(),XPathConstants.NODESET);//user为节点对象(本地实体)
User ru = (User)ctx.createUnmarshaller().unmarshal(nl.item(0));

 

2、解析本地xml文件

Transformer tran = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
tran.transform(new StreamSource(new FileInputStream(new File("test.xml"))), result);

XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList)xpath.evaluate("//对象节点", result.getNode(),XPathConstants.NODESET);
Object obj = (Object)ctx.createUnmarshaller().unmarshal(nl.item(0));

 

你可能感兴趣的:(xpath,解析xml)