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


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

<?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() );
  }
}

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

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 example above ProbeMsg.zip

 

 

 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
64 Java Console and File Input/Output Cheat Sheet 졸리운_곰 2015.07.05 89
63 Demonstrates standard I/O redirection 졸리운_곰 2015.07.05 64
62 [SWING] 분석에 도전해볼만한 오픈소스 WebHarvest Java WebCrawler GUI file 졸리운_곰 2015.05.20 518
61 FreeLayout: A New Java Layout file 졸리운_곰 2015.05.14 140
60 JAVA SWT XML EDITOR sample : 자바 SWT XML 에디터 예제 file 졸리운_곰 2015.05.12 241
59 JAVA SWT 대화상자 예제 : 동적으로 컨트롤을 추가하고 삭제하는 예제 졸리운_곰 2015.05.11 140
58 JAVA SWT LINUX (Ubuntu) 에서 SWT Browser Control 사용시 졸리운_곰 2015.05.10 120
57 JAVA SWT TEST 자료 졸리운_곰 2015.05.07 546
56 SWT 스크롤 ScrolledComposite file 졸리운_곰 2015.05.03 230
55 xerces Xpath - search node from another node 졸리운_곰 2015.04.29 101
54 xerces를 사용한 dom 방식의 xml parser lib 졸리운_곰 2015.04.28 177
53 자바에서 XPath 사용 하기 졸리운_곰 2015.04.28 324
52 Java XML정리 : 노드선택 Select Node(s) 졸리운_곰 2015.04.28 318
51 SWT JAVA 동적으로 컨트롤을 추가하는 다이얼로그2 file 졸리운_곰 2015.04.27 139
50 SWT JAVA 동적으로 컨트롤을 추가하는 다이얼로그 졸리운_곰 2015.04.27 271
49 swt java xulrunner 3.6 캐쉬 비우기 : html 깨짐 졸리운_곰 2015.04.27 166
48 A simple Java console: 졸리운_곰 2015.04.24 131
» XML Processing using XERCES Java Parser file 졸리운_곰 2015.04.22 214
46 SWT – MouseListener & MouseAdapter Example 졸리운_곰 2015.04.22 92
45 JAVA SWT XULRUNNER 브라우저 target=_black 멀티 윈도우 표시 졸리운_곰 2015.04.20 208
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED