xml和javabean互转的方法

转换的工具类:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlUtil {

	private XmlUtil() {
		// Not instantiable
	}

	@SuppressWarnings("unchecked")
	public static <T> T xml2Java(String xml, Class<T> clazz) throws JAXBException {
		T t = null;
		JAXBContext context = JAXBContext.newInstance(clazz);
		Unmarshaller unmarshaller = context.createUnmarshaller();
		t = (T) unmarshaller.unmarshal(new StringReader(xml));
		return t;
	}

	public static String java2Xml(Object obj, String encoding) throws JAXBException {
		String result = null;

		JAXBContext context = JAXBContext.newInstance(obj.getClass());
		Marshaller marshaller = context.createMarshaller();

		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
		marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

		StringWriter writer = new StringWriter();
		marshaller.marshal(obj, writer);
		result = writer.toString();
		return result;
	}

	public static String getNodeText(Document document, String xpath) {
		String nodeText = "";
		Node node = document.selectSingleNode(xpath);
		if (node != null) {
			nodeText = node.getText();
		}
		return nodeText;
	}

	public static String getNodeText(String xml, String xPath)
			throws DocumentException, UnsupportedEncodingException, IOException {
		String nodeText = null;
		try (InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"))) {

			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(is);
			nodeText = XmlUtil.getNodeText(document, xPath);
		}
		return nodeText;
	}

	public static String getElementText(Element parentElement, String elementName) {
		return parentElement.element(elementName).getText();
	}

	public static String getRootNodeName(String xmlData) {
		String rootNodeName = null;
		if (isNotEmpty(xmlData)) {
			int beginIndex = xmlData.indexOf(">") + 1;
			rootNodeName = xmlData.substring(beginIndex);
			if (isNotEmpty(rootNodeName)) {
				// 判断是否有xml文件头
				if (rootNodeName.indexOf("?") > 0) {
					// 第二个<的位置
					int secondGlndex = xmlData.indexOf("<", beginIndex);
					// 第二个>的位置
					int secondLIndex = xmlData.indexOf(">", beginIndex);
					if (secondGlndex < secondLIndex) {
						rootNodeName = xmlData.substring(secondGlndex + 1, secondLIndex);
					}
				} else {
					// 第二个<的位置
					int secondGlndex = xmlData.indexOf("<");
					// 第二个>的位置
					int secondLIndex = xmlData.indexOf(">");
					if (secondGlndex < secondLIndex) {
						rootNodeName = rootNodeName.substring(secondLIndex);
					}
				}
			}
			String[] words = rootNodeName.split("\\s+");
			rootNodeName = words[0];
		}
		return rootNodeName;
	}

	public static String formatXml(String xmlStr,String encoding) throws DocumentException, IOException{
		Document document = null;
		document= DocumentHelper.parseText(xmlStr);
		//格式化输出格式
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding(encoding);
		StringWriter writer = new StringWriter();
		//格式化输出流
		XMLWriter xmlWriter = new XMLWriter(writer,format);
		//将document写入到输出流
		xmlWriter.write(document);
		xmlWriter.close();
		return writer.toString();
	}
	
	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() < 1;
	}

	public static boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}
}

参与转换的java对象:

@XmlRootElement(name="RequestOrder")
public class TitleRequest {
    private List<Item> item =new ArrayList();

    public List<Item> getItem() {
        return item;
    }

    public void setItem(List<Item> item) {
        this.item = item;
    }

    @XmlType(propOrder = { "code","province", "city" ,"district"})
    public static class Item{

        private String code;
        private String province;
        private String city;
        private String district;

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }

        public String getDistrict() {
            return district;
        }

        public void setDistrict(String district) {
            this.district = district;
        }
    }
}

参与转换的xml文件:

<RequestOrder>
    <item>
        <code>EAR201704011459442969</code>
        <province>北京</province>
        <city>北京市</city>
        <district>密云县</district>
    </item>
</RequestOrder>

转换用法:

xmlString = XmlUtil.java2Xml(requestOrder,"UTF-8");


PS:如果需要指定某个节点的名称,而不使用java对象中对应的名称,可是在相应的get方法上加

@XmlElement(name = "area")
public String getDistrict() {
            return district;
}

这样转换成的xml文件就是:


<RequestOrder>
    <item>
        <code>EAR201704011459442969</code>
        <province>北京</province>
        <city>北京市</city>
        <area>密云县</area>
    </item>
</RequestOrder>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值