coding:
public class XmlUtil {
public static final Logger log = LoggerFactory.getLogger(XmlUtil.class);
/**
* @param obj 传入的对象
* @return 返回对象转换xml字符串
*/
public static String objToXmlString(Object obj){
log.info("开始将对象转换为xml格式字符串");
String xmlString = "";
//创建输出 流
StringWriter writer = new StringWriter();
try {
//jdk自带的转换类
//传入对象的class
JAXBContext context = JAXBContext.newInstance(obj.getClass());
//创建marshaller(指挥)通过它可以将xml与对象互相转换 。对于一些不规范的xml格式它也可以进行规范调试
Marshaller marshaller = context.createMarshaller();
//格式化xml输出格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//编码格式
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//去掉默认报文头
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
//将对象输出成XML形式
marshaller.marshal(obj, writer);
xmlString = writer.toString();
} catch (JAXBException e) {
// TODO Auto-generated catch block
log.error("转换出错!",e);
}
return xmlString;
}
public static JSONObject xml2Json(String xmlStr) throws JDOMException, IOException {
if (StringUtils.isEmpty(xmlStr)) {
return null;
}
xmlStr = xmlStr.replaceAll("\\\n", "");
byte[] xml = xmlStr.getBytes("UTF-8");
JSONObject json = new JSONObject();
InputStream is = new ByteArrayInputStream(xml);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
json.put(root.getName(), iterateElement(root));
return json;
}
private static JSONObject iterateElement(Element element) {
List<Element> node = element.getChildren();
JSONObject obj = new JSONObject();
List list = null;
for (Element child : node) {
list = new LinkedList();
String text = child.getTextTrim();
if (StringUtils.isBlank(text)) {
if (child.getChildren().size() == 0) {
continue;
}
if (obj.containsKey(child.getName())) {
list = (List) obj.get(child.getName());
}
//遍历child的子节点
list.add(iterateElement(child));
obj.put(child.getName(), list);
} else {
if (obj.containsKey(child.getName())) {
Object value = obj.get(child.getName());
try {
list = (List) value;
} catch (ClassCastException e) {
list.add(value);
}
}
//child无子节点时直接设置text
if (child.getChildren().size() == 0) {
obj.put(child.getName(), text);
} else {
list.add(text);
obj.put(child.getName(), list);
}
}
}
return obj;
}
}
代码是最好的教程!