본문 바로가기

공부/컴퓨터

XPathAPI를 이용한 간단한 예제 2

반응형
/*
* 작성된 날짜: 2005. 1. 7.
* 만  든  이 : Chan ( http://ggaman.com , chan@ggaman.com )
* 프로젝트명 : XPathTest
* 패키지이름 :
* 화  일  명 : XPathTest2.java
*
* 하  는  일 : {{ 하는 일을 적으세요 ^_^ }}
*
*/

import java.io.IOException;
import java.util.ArrayList;

import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XString;
import org.apache.xpath.objects.XBoolean;
import org.apache.xpath.objects.XNumber;
import org.apache.xpath.objects.XObject;
import org.apache.xpath.objects.XNull;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import org.apache.xpath.objects.XNodeSet;

/**
* @author Chan ( http://ggaman.com , chan@ggaman.com )
*
*/
public class XPathTest2 {
    
    private static final String FILE1_LIST = "student_list.xml";
    private static final String FILE2_INFO = "student_info.xml";
    
    private static final String DOMAIN1 = "//STUDENT";
    private static final String DOMAIN2 = "//INFO";
    private static final String CONDITION = "ID/text()";
    private static final String RETURN = "MAJOR/text()";
    

    public static void main(String[] args) throws SAXException, IOException, TransformerException, ParserConfigurationException {
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = f.newDocumentBuilder();
        
        Document doc1 = docBuilder.parse(FILE1_LIST);
        Document doc2 = docBuilder.parse(FILE2_INFO);
        
        NodeList doc1Result = XPathAPI.selectNodeList(doc1, DOMAIN1);
        NodeList doc2Result = XPathAPI.selectNodeList(doc2, DOMAIN2);
        
        System.out.println("<?xml version="1.0"?>");
        System.out.println("<STUDENTS_MAJOR>");
        
        for ( int i = 0 ; i < doc1Result.getLength() ; i ++ ) {
            Node node1 = XPathAPI.selectSingleNode(doc1Result.item(i),CONDITION);

            for ( int j = 0 ; j < doc2Result.getLength() ; j ++ ) {
                Node node2 = XPathAPI.selectSingleNode(doc2Result.item(j),CONDITION);
                
                if ( node2.getNodeValue().equals(node1.getNodeValue() ) ) {
                    System.out.println(" <STUDENT>");
                    
                    System.out.println(" <ID>" + node2.getNodeValue() + "</ID>");
                    
                    Node _Node = XPathAPI.selectSingleNode(doc2Result.item(i),RETURN);
                    System.out.println(" <MAJOR>" + _Node.getNodeValue() + "</MAJOR>");
                    
                    System.out.println(" </STUDENT>");
                    break;
                }
            }
        }
        System.out.println("</STUDENTS_MAJOR>");
    }
}




반응형