xml格式的解析和转换

来源:互联网 发布:python科学计算张若愚 编辑:程序博客网 时间:2024/04/29 16:01
package com.foresee.dzswj.base.ycs.util;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import java.lang.reflect.InvocationTargetException;import java.util.Iterator;import java.util.List;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.PropertyUtils;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;import org.xml.sax.Attributes;import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.helpers.XMLFilterImpl;import com.foresee.dzswj.base.ycs.util.exception.YcsException;public class JaxbUtil {/** * 清除xml中为空的节点 * @param xml * @return * @throws DocumentException */public static String removeXmlNullElement(String xml)throws YcsException {SAXReader saxReader = new SAXReader();Document document;try {document = saxReader.read(new ByteArrayInputStream(xml.getBytes()));} catch (DocumentException e) {throw new YcsException("处理xml(删除空节点)出错," + e.getMessage());}while (true) {@SuppressWarnings("unchecked")List<Element> list = document.selectNodes("//*[not(node())]");if (list == null || list.size() <= 0) {break;}for (Element e : list) {e.getParent().remove(e);}}String str = document.asXML();return str;}/** * 将xml字符串转为java bean * @param xml * @param claz * @return * @throws JAXBException  */@SuppressWarnings({ "unchecked", "rawtypes" })public static Object transXmlToBean(String xml, Class claz) throws YcsException {DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();    documentBuilderFactory.setNamespaceAware(false);    Object obj;try {DocumentBuilder db = documentBuilderFactory.newDocumentBuilder();org.w3c.dom.Document doc = db.parse(new InputSource(new StringReader(xml)));JAXBContext context = JAXBContext.newInstance(claz);  Unmarshaller unmarshaller = context.createUnmarshaller();  obj = unmarshaller.unmarshal(doc, claz).getValue();} catch (ParserConfigurationException e) {throw new YcsException("xml转bean出错," + e.getMessage());} catch (SAXException e) {e.printStackTrace();throw new YcsException("xml转bean出错," + e.getMessage());} catch (IOException e) {throw new YcsException("xml转bean出错," + e.getMessage());} catch (JAXBException e) {throw new YcsException("xml转bean出错," + e.getMessage());}  return obj;}/** * 将bean转为xml字符串 * @param obj * @return * @throws JAXBException * @throws IOException */public static String transBeanToXml(Object obj) throws YcsException {try {//对申报期初数报文减免信息进行特殊处理,把double的空值节点设置为零Object jmxxGridlb = PropertyUtils.getNestedProperty(obj, "qcs.initData.yhxx.jmxxGrid.jmxxGridlb");if(jmxxGridlb!=null && jmxxGridlb instanceof List){List list=(List) jmxxGridlb;for (Iterator iterator = list.iterator(); iterator.hasNext();) {Object object = (Object) iterator.next();VoUtils.initVoNullProperties(object);}}} catch (Exception e1) {// TODO Auto-generated catch blocke1.printStackTrace();}            Marshaller marshaller;            if (obj == null) {            return null;            }try {JAXBContext context = JAXBContext.newInstance(obj.getClass());marshaller = context.createMarshaller();} catch (JAXBException e) {e.printStackTrace();throw new YcsException("bean转xml出错," + e.getMessage());}            //marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");// //编码格式            //marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);// 是否格式化生成的xml串            //marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);// 是否省略xm头声明信息            StringWriter out = new StringWriter();            XMLWriter writer = new XMLWriter(out);            XMLFilterImpl nsfFilter = new XMLFilterImpl() {                private boolean ignoreNamespace = true;                private String rootNamespace = null;                private boolean isRootElement = true;                @Override                public void startDocument() throws SAXException {                    super.startDocument();                }                @Override                public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {                    if (this.ignoreNamespace) uri = "";                    if (this.isRootElement) this.isRootElement = false;                    else if (!uri.equals("") && !localName.contains("xmlns")) localName = localName + " xmlns=\"" + uri + "\"";                    super.startElement(uri, localName, localName, atts);                }                @Override                public void endElement(String uri, String localName, String qName) throws SAXException {                    if (this.ignoreNamespace) uri = "";                    super.endElement(uri, localName, localName);                }                @Override                public void startPrefixMapping(String prefix, String url) throws SAXException {                    if (this.rootNamespace != null) url = this.rootNamespace;                    if (!this.ignoreNamespace) super.startPrefixMapping("", url);                }            };            nsfFilter.setContentHandler(writer);            try {marshaller.marshal(obj, nsfFilter);} catch (JAXBException e) {throw new YcsException("bean转xml出错," + e.getMessage());}            return out.toString();        }}

0 0
原创粉丝点击