본문 바로가기
JAVA

String 형태의 XML 파싱

by 정윤재 2009. 12. 8.

아래와 같은 XML 형식의 데이터가 String 형태로 전달된다고 하면
(통신에서 많이 쓰더라...)
아래대로 따라가면 충분히 이해할 수 있을 것이라고 생각이 됩니다.
Parsing Util 을 만들어서 쉽게 parsing 할 수 있게 해 놓았습니다.
또한 필요한 jar 파일 또한 올려놓았습니다.

 

<?xml version="1.0" encoding="EUC-KR"?>

< !DOCTYPE info SYSTEM "dtd_dcd_xml_response.dtd" >

     <LOGChannel version="1.0">

         <Head>

             <StateCode>200</StateCode>

             <StateMSG>success</StateMSG>

         </Head>

         <Body>

         <ResultSet state=SUCCESS" rows=3">                      <Step seq=1 time=200909301210" mp_id=1>

                                   <LogMsg></LogMsg>

                                   <ResultCode></ResultCode>

                                   <ResultMsg></ResultMsg>

                      </Step>

                      <Step seq=2 time=" 200909301215 " mp_id=2>

                                   <LogMsg></LogMsg>

                                   <ResultCode></ResultCode>

                                   <ResultMsg></ResultMsg>

                      </Step>

                      <Step seq=3 time=" 200909301215 " mp_id=2>

                                   <LogMsg></LogMsg>

                                   <ResultCode></ResultCode>

                                   <ResultMsg></ResultMsg>

                      </Step>

         </ResultSet>

         </Body>       

     </LOGChannel>

 public static void main(String[] args) {

  XmlPaser xmlPaser = new XmlPaser();

  
  try {

   List outList = xmlPaser.getLogAgentXmlList(XMLDATA);
//XMLDATA는 String 형식의 XML 데이터여야 한다.
if(outList != null && outList.size()>0){
  
  LogAgentXml logAgentXml = new LogAgentXml();
  for(int i=0;i<outList.size();i++){
   logAgentXml   = (LogAgentXml)outList.get(i);
//LogAgentXml 는 DTO 형식의 set get 메소드 형식의 class 다
System.out.println("ResultTitle["+logAgentXml.getResultTitle()+"]");
System.out.println("getTime["+logAgentXml.getTime()+"]");
System.out.println("ResultMsg["+logAgentXml.getResultMsg()+"]");
}//for
   



  } catch (JDOMException e) {
   System.out.println("xmlPaser JDOMException!!");
   e.printStackTrace();
  } catch (Exception e) {
   System.out.println("xmlPaser Exception!!");
   e.printStackTrace();
  }
 }

*************************************************************************
실질적으로 xml parsing 클래스

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;

/**
 * 서비스 확인을 위한 ResultData - XML Paser
 */

 
public class XmlPaser {
 public ErrorHandler errorHandler = null;
 
 /**
  * XmlData를 Log Agent 연동 규격에 맞게 xml Parsiong 하여 LogAgentXml List로   리턴한다.
  * getLogAgentXmlList( String XmlData )
  * return List ( LogAgentXml 객체 리스트)
  */
 public List getLogAgentXmlList( String XmlData ) throws JDOMException,Exception {
  
  SAXBuilder builder = new SAXBuilder();
  if(errorHandler != null){
      builder.setErrorHandler(errorHandler);
     }
     Document document = builder.build( new InputSource(new StringReader(XmlData)) );
    
       List dataList = new ArrayList();
     List elementList = XPathUtil.selectNodeList(document, "/LOGChannel/ResultSet/Step");
//xml 단계 별로 들어가면 된다. xml을 보면 어떻게 쓰는지 알 수 있다.  
  
  for (int i = 0; i < elementList.size(); i++) {
   Element element = (Element) elementList.get(i);
   //step 엘리먼트는 여러개가 나올수 있음
   LogAgentXml logAgentXml = new LogAgentXml();
   
   String time = element.getAttributeValue("time" );
//attribute 인 time 을 string으로 뽑아내기
   String ResultTitle = (String) XPathUtil.selectSingleNode(element, "string(ResultTitle/text())");
   String ResultCode = (String)XPathUtil.selectSingleNode(element, "string(ResultCode/text())");
   String ResultMsg = (String)XPathUtil.selectSingleNode(element, "string(ResultMsg/text())");
   String ResultDescription = (String)XPathUtil.selectSingleNode(element, "string(ResultDescription/text())");
   String ResultLogDetail = (String)XPathUtil.selectSingleNode(element, "string(ResultLogDetail/text())");
   

   logAgentXml.setTime(time);       // 검출된 분석시간
   logAgentXml.setResultTitle(ResultTitle);   // 결과 타이틀 정보
   logAgentXml.setResultCode(ResultCode);    // 결과 코드
   logAgentXml.setResultMsg(ResultMsg);    // 결과 메시지
   logAgentXml.setResultDescription(ResultDescription);// 결과 설명
   logAgentXml.setResultLogDetail(ResultLogDetail); // 결과 상세 정보
   
//   System.out.println("time:"+time);
//   System.out.println("ResultTitle:"+ResultTitle);
//   System.out.println("ResultCode:"+ResultCode);
//   System.out.println("ResultMsg:"+ResultMsg);
//   System.out.println("ResultDescription:"+ResultDescription);
   System.out.println("***********resultLogDetail.get*************************");
   //System.out.println("ResultLogDetail:"+ResultLogDetail);
   System.out.println("ResultLogDetail:"+logAgentXml.getResultLogDetail());
   System.out.println("************************************");
   
   
   dataList.add(logAgentXml);
  }
  return dataList;
 }
}
//*********************************************************************
//XML Util Class (Sax Parser를 사용함)

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.jaxen.JaxenException;
import org.jaxen.XPath;
import org.jaxen.jdom.JDOMXPath;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XPathUtil {
 private static XPath compileExpression(String xpath) {
  XPath xPath = null;
  try {
   xPath = new JDOMXPath(xpath);
  } catch (JaxenException e) {
   e.printStackTrace();
  }
  return xPath;
 }
 public static List selectNodeList(Object node, String _xpath) throws JaxenException {
  XPath xPath = compileExpression(_xpath);
  return xPath.selectNodes(node);
 }
 public static Object selectSingleNode(Object node, String _xpath) throws JaxenException {
 
  XPath xPath = compileExpression(_xpath);
  return xPath.selectSingleNode(node);
 }
 
 public static String getValue(Document document, String _xpath) throws JaxenException {
  List nodes = selectNodeList(document, _xpath);
  String value = null;
  for (int i = 0; i < nodes.size(); i++) {
   Node node = (Node) nodes.get(i);
   if (node.hasChildNodes()) {
    if (node.getNodeType() != 1)
     continue;
    NodeList children = node.getChildNodes();
    int j = 0;
    do {
     if (j >= children.getLength())
      break;
     Node childNode = children.item(j);
     if (childNode.getNodeType() == 3)
      value = childNode.getNodeValue();
     j++;
    } while (true);
   }
   value = node.getNodeValue();
  }
  return value;
 }
 public static String getAttr(Document document, String _xpath, String attr) throws JaxenException {
  List nodes = selectNodeList(document, _xpath);
  String value = null;
  for (int i = 0; i < nodes.size(); i++) {
   Node node = (Node) nodes.get(i);
   NamedNodeMap map = node.getAttributes();
   Node anode = map.getNamedItem(attr);
   value = anode.getNodeValue();
  }
  return value;
 }
 public static String getElementAttr(Element element, String _xpath, String attr) throws JaxenException {
  String value = null;
  NamedNodeMap map = element.getAttributes();
  Node anode = map.getNamedItem(attr);
  value = anode.getNodeValue();
  return value;
 }
 
 public static Map getProperties(Document document) {
  Map map = new HashMap();
  Element list[] = getChildrenByName(document.getDocumentElement(), "property");
  for (int i = 0; i < list.length; i++) {
   String name = list[i].getAttribute("name");
   String type = list[i].getAttribute("type");
   String valueString = getText(list[i]);
   try {
    Class cls = Class.forName(type);
    Constructor con = cls.getConstructor(new Class[] { java.lang.String.class });
    Object value = con.newInstance(new Object[] { valueString });
    map.put(name, value);
   } catch (Exception e) {
    System.err.println("Unable to parse property '" + name + "'='" + valueString + "': " + e);
   }
  }
  return map;
 }
 public static Element getChildByName(Element e, String name) {
  Element list[] = getChildrenByName(e, name);
  if (list.length == 0)
   return null;
  if (list.length > 1)
   throw new IllegalStateException("Too many (" + list.length + ") '" + name + "' elements found!");
  else
   return list[0];
 }
 public static Element[] getChildrenByName(Element e, String name) {
  NodeList nl = e.getChildNodes();
  int max = nl.getLength();
  LinkedList list = new LinkedList();
  for (int i = 0; i < max; i++) {
   Node n = nl.item(i);
   if (n.getNodeType() == 1 && n.getNodeName().equals(name))
    list.add(n);
  }
  return (Element[]) list.toArray(new Element[list.size()]);
 }
 public static String getText(Element e) {
  NodeList nl = e.getChildNodes();
  int max = nl.getLength();
  for (int i = 0; i < max; i++) {
   Node n = nl.item(i);
   //if (!StringUtil.trim(n.getNodeValue()).equals("") && (n.getNodeType() == 3 || n.getNodeType() == 4))
   if (!n.getNodeValue().trim().equals("") && (n.getNodeType() == 3 || n.getNodeType() == 4))
    return n.getNodeValue();
  }

'JAVA' 카테고리의 다른 글

[ JAVA ] URL 클래스 사용 (HTTP 프로토콜로 메시지 송수신)  (1) 2010.02.23
[ JAVA ] 자바 암호화  (0) 2010.02.18
[ JAVA ] 자바 String Util 들  (10) 2009.12.08
자바 날짜 Util  (0) 2009.12.08
[ JAVA ] String 문자열 치환  (0) 2009.12.08

댓글