java实用工具(XML)

package com.omg.web.util;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;

public class XmlUtil {

private static final Log LOG = LogFactory.getLog(XmlUtil.class);

public static String parseXml(String xml, String element) throws Exception {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();

try {
// 通过输入源构造一个Document
Document doc = sb.build(source);
// 取的根元素
Element root = doc.getRootElement();

// 得到根元素所有子元素的集合
List jiedian = root.getChildren();

Element et = null;
for (int i = 0; i < jiedian.size(); i++) {
et = (Element) jiedian.get(i);// 循环依次得到子元素

String name = et.getName();

if (element.equals(name)) {
return et.getText();
}

}

} catch (JDOMException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
return null;
}

/**
* 取得doc
*
* @param xml
* @return
* @throws Exception
*/
public static Document getDocumentByXml(String xml) throws Exception {
try {
StringReader read = new StringReader(xml);
// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
InputSource source = new InputSource(read);
// 创建一个新的SAXBuilder
SAXBuilder sb = new SAXBuilder();

// 通过输入源构造一个Document
return sb.build(source);

} catch (Exception e) {
LOG.error(new XmlUtil(), e);
}
return null;
}

public static Document readMessage(String filePath) throws Exception {
try {
LOG.info("read message file :" + filePath);
File f = new File(filePath);

if (!f.exists()) {
LOG.info("read message file " + filePath + " is empty!");
return null;
}
SAXBuilder sb = new SAXBuilder();
return sb.build(f);
} catch (Exception e) {
LOG.error(new XmlUtil(), e);
}
return null;
}

public static void writeMessage(String filePath, Document doc) throws Exception {
FileOutputStream fos = null;
try {

File f = new File(filePath);

XMLOutputter out = new XMLOutputter();
fos = new FileOutputStream(f);

out.output(doc, fos);
LOG.info("save xml success ..............");
} catch (Exception e) {
LOG.error(new XmlUtil(), e);
} finally {
if (null != fos) {
fos.close();
}
}
}

public static void writeMessage(String filePath, String mobile,
String title, String message, String url) throws Exception {
FileOutputStream fos = null;
try {
FileUtil.createDirectory(filePath);

File f = new File(filePath + mobile + ".xml");

Document doc = null;
if (f.exists()) {
SAXBuilder sb = new SAXBuilder();
doc = sb.build(f);
}

if (null == doc) {
doc = new Document();
}

Element root;
if (doc.hasRootElement()) {
root = doc.getRootElement();
} else {
root = new Element("user");
doc.addContent(root);
}

Element info = new Element("info");

info.addContent(new Element("title").setText(title));
info.addContent(new Element("message").setText(message));
info.addContent(new Element("url").setText(url));

root.addContent(info);

XMLOutputter out = new XMLOutputter();
fos = new FileOutputStream(f);

out.output(doc, fos);
LOG.info(title + " save message success ..............");
} catch (Exception e) {
LOG.error(new XmlUtil(), e);
} finally {
if (null != fos) {
fos.close();
}
}
}

/**
* 解析对象bean
*
* @param <E>
*
* @param xml
* xml内容
* @param cls
* 对象bean
* @return
*/
public static <E> E decodeXml(String xml, Class<E> cls) {
try {
Document doc = XmlUtil.getDocumentByXml(xml);
if (null == doc)
return null;

Element root = doc.getRootElement();
if (null == root)
return null;

List<Element> els = root.getChildren();
// 获取对象bean属性数组
PropertyDescriptor[] props = Introspector.getBeanInfo(cls,
Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors();

E obj = cls.newInstance();
if (null != els && els.size() > 0) {
for (PropertyDescriptor prop : props) {
if (null != prop.getWriteMethod()) {
String text = els.get(0).getChildTextTrim(
StringUtil.getDisplayName(prop));
if (StringUtil.isBlank(text))
text = els.get(0).getChildTextTrim(prop.getDisplayName());
//System.out.println(prop.getDisplayName() + "=" + text);
prop.getWriteMethod().invoke(obj, text);
}
}
}

return obj;
} catch (Exception e) {
LOG.error(new XmlUtil(), e);
}
return null;
}

/**
* 解析成list
*
* @param <E>
*
* @param xml
* xml解析内容
* @param cls
* 对象bean
* @return
*/
public static <E> List<E> decodeXmlList(String xml, Class<E> cls) {
try {
Document doc = XmlUtil.getDocumentByXml(xml);
if (null == doc)
return null;

Element root = doc.getRootElement();
if (null == root)
return null;

List<Element> els = root.getChildren();
List<E> list = new ArrayList<E>();

// 获取对象bean属性数组
PropertyDescriptor[] props = Introspector.getBeanInfo(cls,
Introspector.IGNORE_ALL_BEANINFO).getPropertyDescriptors();

for (Element el : els) {
E obj = cls.newInstance();
for (PropertyDescriptor prop : props) {
if (null != prop.getWriteMethod()) {
String text = el.getChildText(
StringUtil.getDisplayName(prop));
if (StringUtil.isBlank(text))
text = els.get(0).getChildTextTrim(prop.getDisplayName());
//System.out.println(prop.getDisplayName() + "=" + text);
prop.getWriteMethod().invoke(obj, text);
}
}
list.add(obj);
}

return list;
} catch (Exception e) {
LOG.error(new XmlUtil(), e);
}
return null;
}

public static String deleteDom(String xml) throws Exception {
byte[] bs = xml.getBytes();
for (int i=0; i<bs.length; i++) {
if (bs[i] == -17 && bs[i+1] == -69 && bs[i+2] == -65) {
xml = new String(bs, 0, i) + new String(bs, i+3, bs.length - (i+3));
break;
}
}
return xml;
}


public static void main(String[] args) {
try {
String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><tasks><Table><Column1>0</Column1></Table></tasks>";

System.out.println(XmlUtil.getDocumentByXml(XmlUtil.deleteDom(xml)));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值