欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

xml转对象

程序员文章站 2022-05-10 16:49:30
...
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.wutka.jox.JOXBeanInputStream;
import com.wutka.jox.JOXBeanOutputStream;

public class BeanXMLMapping {

    /** *//**
     *  Retrieves a bean object for the
     *  received XML and matching bean class
     */
    public static Object fromXML(String xml, Class className) {
      ByteArrayInputStream xmlData = new ByteArrayInputStream(xml.getBytes());
      JOXBeanInputStream joxIn = new JOXBeanInputStream(xmlData);
      try {
        return (Object) joxIn.readObject(className);
      } catch (IOException exc) {
        exc.printStackTrace();
        return null;
      } finally {
        try {
          xmlData.close();
          joxIn.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    /** *//**
     *  Returns an XML document.nbspString for the received bean
     */
    public static String toXML(Object bean) {
      ByteArrayOutputStream xmlData = new ByteArrayOutputStream();
      JOXBeanOutputStream joxOut = new JOXBeanOutputStream(xmlData);
      try {
        joxOut.writeObject(beanName(bean), bean);
        return xmlData.toString();
      } catch (IOException exc) {
        exc.printStackTrace();
        return null;
      } finally {
        try {
          xmlData.close();
          joxOut.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }

    /** *//**
     *  Find out the bean class name
     */
    private static String beanName(Object bean) {
      String fullClassName = bean.getClass().getName();
      String classNameTemp = fullClassName.substring(
          fullClassName.lastIndexOf(".") + 1,
          fullClassName.length()
          );
      return classNameTemp.substring(0, 1)
           + classNameTemp.substring(1);
    }
    public static void main(String[] args) {
        String content = "<WebAppPolicy lcid=\"1033\"><WebAppPolicyZones><WebAppPolicyZone zonename=\"(All zones)\"/>"
                       + "<WebAppPolicyZone zonename=\"Default\"/></WebAppPolicyZones></WebAppPolicy>";
//        System.out.println(content);
        Object obj = fromXML(content, WebAppPolicy.class);
        WebAppPolicy web = (WebAppPolicy) obj;
        System.out.println(web.getLcid());
        System.out.println(((WebAppPolicy)obj).getLcid());
        System.out.println(((WebAppPolicy)obj).getWebAppPolicyZones().getWebAppPolicyZone()[0].getZonename());
        System.out.println(((WebAppPolicy)obj).getWebAppPolicyZones().getWebAppPolicyZone()[1].getZonename());
    }
  }