java xml

Edit

Castor

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.TestCase;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.ValidationException;

import com.nhncorp.moca.rcv.sample.job.GetMaxMovieInfoForDate;

public class CasterTest extends TestCase {

    public void testCaster() throws IOException, MarshalException, ValidationException{
        // Create a File to marshal to
        GetMaxMovieInfoForDate period = new GetMaxMovieInfoForDate();
        period.setSdate("20080428");
        period.setEdate("20080428");
        FileWriter writer = new FileWriter("test.xml");
        Marshaller.marshal(period, writer);
    }

    public void testCaster2() throws IOException, MarshalException, ValidationException{
        // Create a File to marshal to
        GetMaxMovieInfoForDate period = new GetMaxMovieInfoForDate();
        period.setSdate("20080428");
        period.setEdate("20080428");
        List<GetMaxMovieInfoForDate> list = new ArrayList<GetMaxMovieInfoForDate>();
        list.add(period);
        list.add(period);
        FileWriter writer = new FileWriter("testList.xml");

        // Marshal the person object
        Marshaller.marshal(list, writer);
    }

    public void testCaster3() throws IOException, MarshalException, ValidationException{
        // Create a File to marshal to
        Map<String,String> period = new HashMap<String,String>();
        period.put("sdate","20080428");
        period.put("edate","20080428");
        FileWriter writer = new FileWriter("testMap.xml");
        // Marshal the person object
        Marshaller.marshal(period, writer);
    }
}

XmlBeans

JiBX

XStream

XStream is an XML serialization library, not a data binding library. Therefore, it has limited namespace support. As such, it is rather unsuitable for usage within Web services.

import java.util.HashMap;
import java.util.Map;

import junit.framework.TestCase;

import com.nhncorp.moca.rcv.sample.job.GetMaxMovieInfoForDate;
import com.thoughtworks.xstream.XStream;

public class XStreamTest extends TestCase {

    public void testXStream(){
        XStream xstream = new XStream();
        GetMaxMovieInfoForDate period = new GetMaxMovieInfoForDate();
        period.setSdate("20080428");
        period.setEdate("20080428");
        xstream.alias("period", GetMaxMovieInfoForDate.class);
        String result = xstream.toXML(period);
        System.out.println(result);
    }

    public void testXStreamMap(){
        XStream xstream = new XStream();
        Map<String,String> period = new HashMap<String,String>();
        period.put("sdate","20080428");
        period.put("edate","20080428");
        String result = xstream.toXML(period);
        System.out.println(result);
    }
}

StAX

Streaming API for XML (StAX) . JSR-173에 기초 JAXP 1.4의 일부분

SAX는 이벤트 핸들러가 parser로 부터 event를 받는 것이라서 사용자는 call back 메소드를 통해서만 이를 처리할 수 있다.

어플리케이션 코드가 그것을 당겨서 받아올수 있다는 것. (pull-based approach) parsing process의 control을 직접 유지할 수 있다.

JDOM

JDOM : JAXP의 DOM 트리가 프로그래밍 언어에 독립적으로 정의되었기 되어서 Java언어에서 다루기가 자연스럽지 못하다는 단점이 있음. JDOM은 좀더 자바 언어에 최적화된 DOM 트리를 구성.

Sample1

public static Document getDocument(String xmlPath) throws Exception {

    InputStream in = null;

    if (xmlPath.indexOf("<?") < 0) { // 경로가 입력된 경우
        in = new FileInputStream(xmlPath);
    } else { // XML String이 입력된 경우
        in = new ByteArrayInputStream(xmlPath.getBytes());
    }

    SAXBuilder builder = new SAXBuilder(false);
    Document configDoc = builder.build(in);
    in.close();
    return configDoc;
}

JAXP

abstraction layer

javax.xml.parsers는 SAXParserFactory와 DocumentBuilderFactory 제공

Sample - SAX

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
parser.parse(filename, new DefaultHandler());

Sample - DOM

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(filename);

Sample - XSLT 프로세서 생성 예제

TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer( new SAXSource(new InputSource(stylesheetFile)));
transformer.transform( new SAXSource(new InputSource(XMLFilename)), new StreamResult(resultFilename));

JAXB

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.1</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>2.1.9</version>
</dependency>

Digester

event 기반인 SAX를 내부적으로 사용

Digester 클래스는 org.xml.sax.ContentHandler를 구현하고 있으며, parse stack를 관리하고

Rule 샘플

package prototype.common;

import java.util.Map;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.digester.BeanPropertySetterRule;

public class BeanAndMapPropertySetterRule extends BeanPropertySetterRule {

    public BeanAndMapPropertySetterRule(String propertyName){
        super(propertyName);
    }
    public void end(String namespace, String name)    throws Exception{
        Object top = digester.peek();
        if(top instanceof Map)  {
            PropertyUtils.setProperty(top, propertyName, bodyText);
        } else {
            super.end(namespace,name);
        }
    }
}

java XML 발표준비

Java의 표준 XML 처리 API

구현체는 Crimson, Xercers2

오픈소스API

Map vs VO

31MB 파일처리시 속도는 3배이상

참고자료

Spring OXM

Spring WS

소스 보기

XML web service