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



본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
18 스프링(Spring) 프레임워크 기본 개념 강좌 (7) - Patterns 졸리운_곰 2017.10.02 262
17 스프링(Spring) 프레임워크 기본 개념 강좌 (6) - Dynamic Proxy 졸리운_곰 2017.10.02 257
16 스프링(Spring) 프레임워크 기본 개념 강좌 (5) - AOP Proxy file 졸리운_곰 2017.10.02 309
15 스프링(Spring) 프레임워크 기본 개념 강좌 (4) - AOP file 졸리운_곰 2017.10.02 288
14 스프링(Spring) 프레임워크 기본 개념 강좌 (3) - IoC file 졸리운_곰 2017.10.02 379
13 스프링(Spring) 프레임워크 기본 개념 강좌 (2) - 주요 구성 요소 & DI file 졸리운_곰 2017.10.02 323
12 스프링(Spring) 프레임워크 기본 개념 강좌 (1) - 스프링 이해하기 file 졸리운_곰 2017.10.02 573
11 Spring - IoC & DI file 졸리운_곰 2017.10.02 238
10 MyBatis 기본 - selectList file 졸리운_곰 2016.06.07 493
9 Mybatis ResultMap 그리고 select 졸리운_곰 2016.06.07 424
8 Cliche Command-Line Shell file 졸리운_곰 2015.07.12 726
7 [스프링] 스프링 Java 어노테이션 file 졸리운_곰 2014.06.11 960
6 [스프링] 스프링 MVC 졸리운_곰 2014.06.11 533
5 [스프링] 어노테이션 졸리운_곰 2014.06.11 1033
4 [Spring] @Autowired 와 Java Spring 졸리운_곰 2014.01.29 1332
3 [Spring] 내가 Spring을 사랑하는 다섯 가지 이유 file 가을의 곰을... 2013.12.22 970
2 [Spring] VO 객체의 복사 가을의 곰을... 2013.11.26 4289
1 [Spring] Spring MVC Basics file 가을의 곰을... 2013.10.09 918
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED