XML Processing using XERCES Java Parser


Karl Seematter, Akadia AG, Information Technology, CH-3604 Thun
Phone: +41 33 335 86 24 / Fax: +41 33 335 86 25 /
EMail: karl.seematter@akadia.com


[출처] http://www.akadia.com/services/java_xml_parser.html

         


Using XML to transport information between different systems is nowadays a state of the art technology. Searching the WEB you'll find a huge set of examples how to validate and parse an XML document. But when it comes to the point where you have to create a XML document and send it as stream (i.g. character-stream, string, byte-array, etc.) to another system, it becomes difficult to find a proper example. Furthermore, different implementations of the DOM specification using different class names to do the same thing.

Here comes an example which creates a XML Document using DOM and transforms it to a String. We used the XERCES Java Parser V1_4_3 from apache.org.

Xerces (named after the Xerces Blue butterfly) provides world-class XML parsing and generation. Fully-validating parsers are available for both Java and C++, implementing the W3C XML and DOM (Level 1 and 2) standards, as well as the de facto SAX (version 2) standard. The parsers are highly modular and configurable. Initial support for XML Schema (draft W3C standard) is also provided.

Runing the example produces the following output

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

<?xml version="1.0" encoding="UTF-8"?>
<ProbeMsg>
  <TimeStamp>2001-11-30T09:08:07Z</TimeStamp>
  <ProbeId>1A6F</ProbeId>
  <ProbeValue ScaleUnit="mm">1245</ProbeValue>
</ProbeMsg>

Here is the Java Code: for ProbeMsg.java

import java.io.*;
import java.util.*;
import java.text.*;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
import org.apache.xerces.jaxp.DocumentBuilderImpl;
import org.apache.xml.serialize.XMLSerializer;
import org.apache.xml.serialize.OutputFormat;

public class ProbeMsg {

   // XML tag's
   private static final String TAG_PROBE_MSG      = "ProbeMsg";
   private static final String TAG_TIMESTAMP      = "TimeStamp";
   private static final String TAG_PROPE_ID       = "ProbeId";
   private static final String TAG_PROPE_VALUE    = "ProbeValue";

   // XML Settings
   private static final String XML_VERSION        = "1.0";
   private static final String XML_ENCODING       = "UTF-8";

   // Format definitions
   private static final String DATE_TIME_FORMAT   =
     "yyyy-MM-dd'T'HH:mm:ss'Z'";

   // Variables
   private Date     msgTimeStamp  = null;
   private String   probeId       = "";
   private Integer  probeValue    = null;
   private Document xmlDoc        = null;
   private String   xmlStr        = null;

    // Constructor
    public ProbeMsg(Date   pTimeStamp
                  ,String pProbeId
                   ,int    pProbeValue ) {

      this.msgTimeStamp = pTimeStamp;
      this.probeId      = pProbeId;
      this.probeValue   = new Integer(pProbeValue);

     // Generate the XML Document using DOM
      this.generateXMLDocument();

      // Generate a XML String
      this.generateXMLString();
    }

    // Retrive probe message as XML string
   public String getXMLString() {
      return xmlStr;
    }

    // Generate a DOM XML document
    private void generateXMLDocument()
    {
     Element main;
     Element root;
     Element item;
      DateFormat timeStampFormat =
      new SimpleDateFormat( DATE_TIME_FORMAT );

    try {

      //Create a XML Document
      DocumentBuilderFactory dbFactory =
        DocumentBuilderFactoryImpl.newInstance();
      DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
      xmlDoc = docBuilder.newDocument();
    } catch(Exception e) {
        System.out.println("Error " + e);
    }

    // Create the root element
    root = xmlDoc.createElement(TAG_PROBE_MSG);

    // Add TimeStamp Element and its value
    item = xmlDoc.createElement(TAG_TIMESTAMP);
    item.appendChild(xmlDoc.createTextNode(
      timeStampFormat.format(msgTimeStamp)));
    root.appendChild(item);

    // Add ProbeId Element and its value
    item = xmlDoc.createElement(TAG_PROPE_ID);
    item.appendChild(xmlDoc.createTextNode(probeId));
    root.appendChild(item);

    // Add ProbeValue Element and its value
    item = xmlDoc.createElement(TAG_PROPE_VALUE);
    item.appendChild(xmlDoc.createTextNode(probeValue.toString() ));
    item.setAttribute("ScaleUnit", "mm");
    root.appendChild(item);

    // Add to the root Element
    xmlDoc.appendChild(root);

  }

  // Generate String out of the XML document object
  private void generateXMLString() {

    StringWriter  strWriter    = null;
    XMLSerializer probeMsgSerializer   = null;
    OutputFormat  outFormat    = null;

    try {
      probeMsgSerializer = new XMLSerializer();
      strWriter = new StringWriter();
      outFormat = new OutputFormat();

      // Setup format settings
      outFormat.setEncoding(XML_ENCODING);
      outFormat.setVersion(XML_VERSION);
      outFormat.setIndenting(true);
      outFormat.setIndent(4);

      // Define a Writer
      probeMsgSerializer.setOutputCharStream(strWriter);

      // Apply the format settings
      probeMsgSerializer.setOutputFormat(outFormat);

      // Serialize XML Document
      probeMsgSerializer.serialize(xmlDoc);
      this.xmlStr = strWriter.toString();
      strWriter.close();

    } catch (IOException ioEx) {
        System.out.println("Error " + ioEx);
    }
  }

  public static void main (String argv[]) {

    ProbeMsg pMsg = new ProbeMsg(new Date()   // Timestamp
                                ,"1A6F"       // Probe ID
                                ,1245);       // Probe Value
    System.out.println(pMsg.getXMLString() );
  }
}

Compile the Code with

javac -classpath ".;C:\java\xerces-1_4_3\xerces.jar" ProbeMsg.java

Run the Code with

java -classpath ".;C:\java\xerces-1_4_3\xerces.jar" ProbeMsg

Links and Download

Logging: log4j http://jakarta.apache.org/log4j/docs/index.html
Xml dom: jdom http://www.jdom.org/
Xml parser and others: xerces http://xml.apache.org/

Download above example



본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
» Java XML Parse, Java XML 파싱 샘플 졸리운_곰 2015.03.03 814
29 Java Inner class 자바 중첩(내부)클래스 졸리운_곰 2015.03.03 886
28 IzPack으로 GUI 설치 프로그램 만들기 file 졸리운_곰 2015.02.15 638
27 [Java],[AWT],[Layout],[AWT Layout], file 졸리운_곰 2015.02.13 368
26 [Java],[AWT],[SWING], Java GUI file 졸리운_곰 2015.02.13 922
25 [Java][AWT 개요] file 졸리운_곰 2015.02.13 463
24 javac 로 컴파일 시 유니코드(utf-8) 한글 소스 코드 컴파일 문제 졸리운_곰 2015.02.02 1133
23 [스프링] 스프링 Java 어노테이션 file 졸리운_곰 2014.06.11 960
22 [스프링] 스프링 MVC 졸리운_곰 2014.06.11 532
21 [스프링] 어노테이션 졸리운_곰 2014.06.11 1032
20 인코딩 - 8859_1의 비밀(?) file 졸리운_곰 2014.05.06 581
19 [JNI] 안드로이드 JNI 환경에서 C++과 Java 간의 한글 데이터 전송 문제 졸리운_곰 2014.05.06 597
18 자바 암호화 복호화 file 졸리운_곰 2014.04.08 2495
17 파일 존재 여부 판단, 디렉토리 있는지 확인 함수; File Directory Exist 졸리운_곰 2014.03.03 1215
16 NetStat call and get result text in Java 졸리운_곰 2014.02.25 903
15 [Spring] @Autowired 와 Java Spring 졸리운_곰 2014.01.29 1332
14 Java Static 변수 졸리운_곰 2014.01.28 1102
13 Properties 클래스 사용하기. 졸리운_곰 2014.01.28 1024
12 Java => Thread 졸리운_곰 2014.01.28 834
11 [Spring] 내가 Spring을 사랑하는 다섯 가지 이유 file 가을의 곰을... 2013.12.22 970
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED