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
'JAVA' 카테고리의 다른 글
JAVA로 영문 대,소문자+숫자 난수 발생시키기 (0) | 2014.02.28 |
---|---|
Random 클래스를 이용하여 영문+숫자 랜덤코드 만들기 (0) | 2014.02.28 |
[readLine] File 내용을 String 으로 읽어오기 (0) | 2014.02.28 |
SimpleDateFormat 보단 FastDateFormat을 이용하자. (0) | 2014.02.28 |
자바 소켓(java socket) InputStreamReader를 사용한 기초적 사용 (0) | 2014.02.19 |
자바 소켓( java socket ) 가장기초 server client (0) | 2014.02.19 |
JAVA 하루전날짜 구하는 메소드 (0) | 2014.02.19 |
Java POI로 엑셀 파일 조작하기 (0) | 2014.02.19 |