用Dom4j解析XML XMLParserHelperDom4j

import java.io.File;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;

public class XMLParserHelperDom4j
{
private static Logger log = Logger.getLogger(XMLParserHelperDom4j.class); // 日志

public static final String ORIGINALL_VALUE = "OriginallyValue";

public static final String TRANSFER_VALUE = "TransferValue";

/**
* 获取key节点的值
* @param el
* @param key
* @return
* @throws Exception
*/
public static String getText(Element el, String key)
{
Element tmp = null;

if (el == null)
{
return null;
}
else
{
tmp = getElement(el, null, key);
}
return tmp.getText();
}

/**
* 获取节点的下级节点key的节点
* @param el
* @param namespace
* @param key
* @return
*/
public static Element getElement(Element el, String namespace, String key)
{
if (el == null)
return null;

try
{
return el.element(key);
}
catch (RuntimeException e)
{
// 找不到对应的节点,可以忽略
log.warn("Can not found the node[" + key + "]:" + e.toString());

return null;
}
}

public static Element parserXML(String inputXML)
{
SAXReader reader = new SAXReader();
Document document = null;
Element rootElement = null;
try
{
reader.setFeature(
"http://apache.org/xml/features/nonvalidating/load-external-dtd",
false);
File f = new File(inputXML);

// 转换成UTF-8格式
/*
* fis = new FileInputStream(f); StringBuffer sb = new
* StringBuffer(""); byte[] bt = new byte[1024]; while (fis.read(bt)
* > 0) { sb.append(new String(bt)); } ByteArrayInputStream in = new
* ByteArrayInputStream(sb.toString() .getBytes());
* InputStreamReader utf8In = new InputStreamReader(in, "UTF-8");
*/
// 解析XML
document = reader.read(f);
// 获取根元素
rootElement = document.getRootElement();

}
catch (SAXException e)
{
// TODO Auto-generated catch block
log.error(e.getMessage(),e);
}
catch (DocumentException e)
{
// TODO Auto-generated catch block
log.error(e.getMessage(),e);
}
catch (Exception e)
{
// TODO Auto-generated catch block
log.error(e.getMessage(),e);
}

return rootElement;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值