code pieces xml parse

1.xml parse to object

 

package com.tien.util;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
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;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * @author xt40919
 * @version Create Time:May 12, 2011 1:21:01 PM
 */

public class XMLParseObjectTools {

    /**
     * @param string, Object
     * English:get data from xml and parse to new Object
     * Chinese:把xml数据转换成对象
     */
    public static Object convertXMLStringToObject(String xml, Object object) {
        Map<String, String> objectsAttrs = new HashMap<String, String>();
        try {
            DocumentBuilderFactory domFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder dombuilder = domFactory.newDocumentBuilder();
            try {
                Document doc = dombuilder.parse(new InputSource(
                        new StringReader(xml)));
                Element root = doc.getDocumentElement();
                NodeList nodes = root.getChildNodes();

                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    NamedNodeMap attributes = node.getAttributes();
                    if (attributes != null)
                        objectsAttrs.put(attributes.item(0).getNodeValue(),
                                attributes.item(1).getNodeValue());
                }
                if(object != null){
                    object = convertToObject(objectsAttrs, object);
                    return object;
                }
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
        return objectsAttrs;
    }
    /*
     * English: xml map data parse to Object attritue data
     * Chinese:xml 里面的数据自动填充到java对象里面
     */
    private static Object convertToObject(final Map<String, String> mappAttr, final Object object){
        for (final String columnName : mappAttr.keySet()) {
            ReflectionUtils.doWithFields(object.getClass(),
                    new FieldCallback() {
                        public void doWith(Field field) {
                            if (columnName
                                    .equalsIgnoreCase(field
                                            .getName())) {
                                Object obj = null;
                                try {
                                    obj = mappAttr.get(columnName);
                                } catch (Exception e) {
                                }
                                try {
                                    BeanUtils.setProperty(
                                            object, field
                                                    .getName(),
                                            obj);
                                } catch (IllegalAccessException e) {
                                    e.printStackTrace();
                                } catch (InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
        }
        return object;
    }

    /*
     *
     * Only for Doc test
     */
    public static void main(String[] args) {
        String XMLString =
         "<Root subject=/"List/"><Field name=/"update/" value=/"1304019065498/"/><Field name=/"Groups/" value=/"abc, abc, abc/"/></Root>";
        DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder dombuilder = domfac.newDocumentBuilder();
            try {
                Document doc = dombuilder.parse(new InputSource(
                        new StringReader(XMLString)));
                Element root = doc.getDocumentElement();
                NodeList nodes = root.getChildNodes();
                Map<String, String> mapAttr = new HashMap<String, String>();
                for (int i = 0; i < nodes.getLength(); i++) {
                    Node node = nodes.item(i);
                    // System.out.println(node.getNodeName());
                    // System.out.println(node.getAttributes());
                    NamedNodeMap attributes = node.getAttributes();
                    if (attributes != null)
                        mapAttr.put(attributes.item(0).getNodeValue(),
                                attributes.item(1).getNodeValue());
                }
                System.out.println(mapAttr);
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值