Skip to content

Instantly share code, notes, and snippets.

@haebi
Last active November 2, 2017 02:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haebi/29070dda0556fc6fba5909b45a067faa to your computer and use it in GitHub Desktop.
Save haebi/29070dda0556fc6fba5909b45a067faa to your computer and use it in GitHub Desktop.
Parse XML with Java XPath Example Code
package xmlparse2;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class XmlParse2 {
public static void main(String[] args) throws Exception {
// 샘플 XML 파일(books.xml)
// [REF] https://msdn.microsoft.com/ko-kr/library/ms762271(v=vs.85).aspx
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("http://haebi.net/book.xml");
// XPath 인스턴스 생성
XPath xpath = XPathFactory.newInstance().newXPath();
// 대상 노드 지정
String expression = "/catalog/book";
// 지정 노드로 부터 노드목록 획득
NodeList nl = (NodeList) xpath.evaluate(expression, doc, XPathConstants.NODESET);
// 첫번째 노드의 부모 노드명을 출력
System.out.println(nl.item(0).getParentNode().getNodeName());
System.out.println("sub node start!!");
System.out.println("-----------------------------------------------------");
// 1번째 book 노드의 자식노드 목록을 획득
NodeList cnl = nl.item(0).getChildNodes(); // author, title, genre, price, publish_date, description
System.out.println(cnl.item(0).getParentNode().getNodeName());
// 확보된 노드 목록을 순서대로 출력
for(int i=0; i<cnl.getLength(); i++)
{
// 노드 이름이 #text로 출력되는 문제로 스킵 하도록 설정하였다.
// xml파일의 들여쓰기로 인한 문제 인듯 하다.
if("#text".equals(cnl.item(i).getNodeName()))
continue;
// 현재 노드 인덱스 번호 출력
System.out.println(i);
// 노드 명 출력
System.out.println("NODE : " + cnl.item(i).getNodeName());
// 노드 값 출력
System.out.println("VALUE : " + cnl.item(i).getTextContent());
}
System.out.println("-----------------------------------------------------");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment