Xpath 테스트

JAVA 2014. 2. 19. 13:43
728x90
반응형

package test;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XpathTest {

 
 //Dom document객체로 문서를 로딩
 //문서를 파싱하고 상응하는 Document객체를 만드는 코드
 
 public static void main(String args[])
 throws ParserConfigurationException, SAXException,
 IOException, XPathExpressionException
 {
  DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
  
  domFactory.setNamespaceAware(true);  //never forget this
  
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  
  Document doc = builder.parse("test/books.xml");
  
  XPathFactory factory =XPathFactory.newInstance();
  
  XPath xpath = factory.newXPath();
  
  XPathExpression expr = xpath.compile("//book[@year='2005']/title[@name='2060']/text()");
  
  Object result = expr.evaluate(doc, XPathConstants.NODESET);

  NodeList nodes = (NodeList) result;
  
  for (int i = 0; i < nodes.getLength(); i++) {
   System.out.println(nodes.item(i).getNodeValue());
   
  }
  
  
 }
 
 
}

 

 

XpathTest.java

 

 

<?xml version="1.0" encoding="UTF-8"?>

<inventory>
 <book year="2000">
  <title>Snow Crash</title>
  <author>Neal stephenson</author>
  <publisher>Spectra</publisher>
  <isbn>0553380958</isbn>
  <price>14.95</price>
 </book>
 <book year="2005">
  <title>Burning Tower</title>
  <title>Burning Tower1</title>
  <title>Burning Tower2</title>
  <title>Burning Tower3</title>
  <title>Burning Tower4</title>
  <title>Burning Tower5</title>
  <title>Burning Tower6</title>
  <title>Burning Tower7</title>
  <title>Burning Tower8</title>
  <title>Burning Tower9</title>
  <title name="2030">Burning Tower101234234234</title>
  <title name="2060">Burning Tower1182410</title>
  <author>Jerry Pournelle</author>
  <isbn name="2040">0743416910</isbn>
  <price name="2050">5.99</price>
 </book>
 <book year="1995">
  <title>Zodiac</title>
  <author>Neal Stephenson</author>
  <publisher>Spectra</publisher>
  <isbn>0553573862</isbn>
  <price>7.50</price>
 </book>
</inventory>

 

 

books.html

728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,