您的位置:首页 > 编程语言 > Java开发

BaseCode之XML工具类:XMLUtil.java

2017-06-13 20:08 323 查看
XMLUtil.java

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class XMLUtil
{

public static Document read(String path) throws DocumentException
{

SAXReader reader = new SAXReader();

InputStreamReader is = new InputStreamReader(new XMLUtil().getClass().getResourceAsStream(path), Charset.forName("GBK"));

Document document = reader.read(is);

return document;
}

public static String getSubElementText(Element element, String name)
{

if (element == null)
{
return null;
}
Iterator iterator = element.elementIterator(name);

if (iterator.hasNext())
{
Element temp = (Element)iterator.next();
return temp.getText();
}
else
{
return null;
}
}

public static Element getElementByMap(Map valueMap, String headName, String[] sort)
{
if (valueMap == null || headName == null || headName.equals(""))
{
throw new RuntimeException("getElementByMap方法参数不能为空!valueMap=" + valueMap + " headname = " + headName);
}
Element element = DocumentHelper.createElement(headName);
for (int i = 0; i < sort.length; i++)
{
String key = sort[i];
String value = (String)valueMap.get(key);
value=value==null?"":value;//过滤null情况
element.addElement(key).addText(value);
}
return element;
}

public static String getElementXmlByMap(Map valueMap, String headName, String[] sort)
{
return getElementByMap(valueMap, headName, sort).asXML();
}

public static Map getMapByXML(Element element)
{
Map returnMap = new HashMap();
for (Iterator iter = element.elementIterator(); iter.hasNext();)
{
Element e = (Element)iter.next();
if (e.isTextOnly())
{
String key = e.getName();
String value = e.getText();
returnMap.put(key, value);
}
}
return returnMap;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: