XML 实用工具类

xml

package com.elink.util;

/*
* <p>Company: 凌科软件 www.elingke.com </p>
* @author liubaojun
* @version 1.0
* Created on 2004-11-29
* 来源于 elinkBSP 部分源代码
*/

import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;

import org.w3c.dom.*;
import org.xml.sax.*;

public class XmlUtil
{
public static synchronized Document newDocument()
{
Document doc = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
doc = db.newDocument();
}
catch (Exception e)
{
LogUtil.logException( e );
}
return doc;
}

public static synchronized Element createRootElement()
{
Element rootElement = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
Document doc = db.newDocument();
rootElement = doc.getDocumentElement();
}
catch (Exception e)
{
e.printStackTrace();
}
return rootElement;
}

public static synchronized Element getRootElement(String fileName)
{
if (fileName == null || fileName.length() == 0)
{
return null;
}
try
{
Element rootElement = null;
FileInputStream fis = new FileInputStream(fileName);
rootElement = getRootElement(fis);
fis.close();
return rootElement;
}
catch (Exception e)
{
return null;
}
}

public static synchronized Element getRootElement(InputStream is)
{
if (is == null)
{
return null;
}
Element rootElement = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
Document doc = db.parse(is);
rootElement = doc.getDocumentElement();
}
catch (Exception e)
{
e.printStackTrace();
}
return rootElement;
}

public static synchronized Element getRootElement(InputSource is)
{
if (is == null)
{
return null;
}
Element rootElement = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().
newDocumentBuilder();
Document doc = db.parse(is);
rootElement = doc.getDocumentElement();
}
catch (Exception e)
{
e.printStackTrace();
}
return rootElement;
}

public static synchronized Element[] getChildElements(Element element)
{
if (element == null)
{
return null;
}
Vector childs = new Vector();
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
childs.add( (Element)node);
}
}
Element[] elmt = new Element[childs.size()];
childs.toArray(elmt);
return elmt;
}

public static synchronized Element[] getChildElements(Element element,
String childName)
{
if (element == null || childName == null || childName.length() == 0)
{
return null;
}
Vector childs = new Vector();
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
if (node.getNodeName().equals(childName))
{
childs.add( (Element)node);
}
}
}
Element[] elmt = new Element[childs.size()];
childs.toArray(elmt);
return elmt;
}

public static synchronized Node[] getChildNodes(Node node)
{
if (node == null)
{
return null;
}
Vector childs = new Vector();
for (Node n = node.getFirstChild(); n != null;
n = n.getNextSibling())
{
childs.add( (Element)n);
}
Node[] childNodes = new Element[childs.size()];
childs.toArray(childNodes);
return childNodes;
}

public static synchronized Element getChildElement(Element element,
String childName)
{
if (element == null || childName == null || childName.length() == 0)
{
return null;
}
Element childs = null;
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
if (node.getNodeName().equals(childName))
{
childs = (Element)node;
break;
}
}
}
return childs;
}

public static synchronized Element getChildElement(Element element)
{
if (element == null)
{
return null;
}
Element childs = null;
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Element)
{
childs = (Element)node;
break;
}
}
return childs;
}

public static synchronized String[] getElenentValues(Element element)
{
if (element == null)
{
return null;
}
Vector childs = new Vector();
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Text)
{
childs.add(node.getNodeValue());
}
}
String[] values = new String[childs.size()];
childs.toArray(values);
return values;
}

public static synchronized String getElenentValue(Element element)
{
if (element == null)
{
return null;
}
String retnStr = null;
for (Node node = element.getFirstChild(); node != null;
node = node.getNextSibling())
{
if (node instanceof Text)
{
String str = node.getNodeValue();
if (str == null || str.length() == 0
|| str.trim().length() == 0)
{
continue;
}
else
{
retnStr = str;
break;
}
}
}
return retnStr;
}

public static synchronized Element findElementByName(Element e, String name)
{
if (e == null || name == null || name.length() == 0)
{
return null;
}
String nodename = null;
Element[] childs = getChildElements(e);
for (int i = 0; i < childs.length; i++)
{
nodename = childs[i].getNodeName();
if (name.equals(nodename))
{
return childs[i];
}
}
for (int i = 0; i < childs.length; i++)
{
Element retn = findElementByName(childs[i], name);
if (retn != null)
{
return retn;
}
}
return null;
}
public static synchronized Element findElementByAttr(Element e, String attrName,
String attrVal)
{
return findElementByAttr( e, attrName, attrVal, true );
}

public static synchronized Element findElementByAttr(Element e, String attrName,
String attrVal, boolean dept)
{
if (e == null || attrName == null || attrName.length() == 0
|| attrVal == null || attrVal.length() == 0)
{
return null;
}
String tmpValue = null;
Element[] childs = getChildElements(e);
for (int i = 0; i < childs.length; i++)
{
tmpValue = childs[i].getAttribute(attrName);
if (attrVal.equals(tmpValue))
{
return childs[i];
}
}
if( dept )
{
for (int i = 0; i < childs.length; i++)
{
Element retn = findElementByAttr(childs[i], attrName, attrVal);
if (retn != null)
{
return retn;
}
}
}
return null;
}

public static synchronized String formatXml(Element e)
{
return formatXml(e, 0);
}

/**
* 格式化XML输出串.
*/
public static synchronized String formatXml(Element e, int indent)
{
indent++;
for (Node n = e.getFirstChild(); n != null; n = n.getNextSibling())
{
appendIndent(e, n, indent);
if (!n.getNodeName().equals("#text"))
{
formatXml( (Element)n, indent);
}
}
indent--;
appendIndent(e, indent);
return e.toString();
}

/**
* 在指定的节点前插入格式表示.
*/
private static synchronized void appendIndent(Element e, Node pos, int indent)
{
Document doc = e.getOwnerDocument();
if (indent == 0)
{
e.insertBefore(doc.createTextNode("\n"), pos);
}
for (int i = 0; i < indent; i++)
{
if (i == 0)
{
e.insertBefore(doc.createTextNode("\n\t"), pos);
}
else
{
e.insertBefore(doc.createTextNode("\t"), pos);
}
}
}

/**
* 追加格式表示.
*/
private static synchronized void appendIndent(Element e, int indent)
{
Document doc = e.getOwnerDocument();
if (indent == 0)
{
e.appendChild(doc.createTextNode("\n"));
}
for (int i = 0; i < indent; i++)
{
if (i == 0)
{
e.appendChild(doc.createTextNode("\n\t"));
}
else
{
e.appendChild(doc.createTextNode("\t"));
}
}
}

public static synchronized void setAttribute(Element e, String name, String value)
{
if (e == null || name == null || name.length() == 0 || value == null
|| value.length() == 0)
return;
else
e.setAttribute( name, value );
}

public static synchronized String getAttribute(Element e, String name)
{
return getAttribute( e, name, null );
}
public static synchronized String getAttribute(Element e, String name, String defval)
{
if( e == null || name == null || name.length()== 0 )
return defval;
else
return e.getAttribute(name);
}

public void transformerWrite( Element doc, String filename ) throws Exception
{
DOMSource doms = new DOMSource( doc );
File f = new File( filename );
StreamResult sr = new StreamResult( f );
transformerWrite( doms, sr );
}

public void transformerWrite( Element doc, File file ) throws Exception
{
DOMSource doms = new DOMSource( doc );
StreamResult sr = new StreamResult( file );
transformerWrite( doms, sr );
}

public void transformerWrite( Element doc, OutputStream outstream ) throws Exception
{
DOMSource doms = new DOMSource( doc );
StreamResult sr = new StreamResult( outstream );
transformerWrite( doms, sr );
}

public void transformerWrite( Element doc, Writer outwriter ) throws Exception
{
DOMSource doms = new DOMSource( doc );
StreamResult sr = new StreamResult( outwriter );
transformerWrite( doms, sr );
}

public void transformerWrite( DOMSource doms, StreamResult sr ) throws Exception
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty( OutputKeys.ENCODING, "GBK" );
t.transform( doms, sr );
}
}

时间: 2024-11-05 09:14:32

XML 实用工具类的相关文章

Pig系统分析(7) Pig实用工具类

Explain Explain是Pig提供的调试工具,使用explain可以输出Pig Lation的执行计划.值得一提的是,explain支持-dot选项,将执行计划以DOT格式输出, (DOT是一种图形描述语言,请参考http://zh.wikipedia.org/zh/DOT%E8%AF%AD%E8%A8%80) 代码实现详见org.apache.pig.impl.plan.DotPlanDumper,这部分实现为我们设计执行计划可视化提供了参考. 下图部分截取了使用Graphviz打开物

分页封装实用工具类及其使用方法

分页封装实用工具类及其使用方法 作者: javaboy2012 Email:yanek@163.com qq:    1046011462     package com.yanek.util; import java.util.List; public class PageBean { /** * @param args */ public static void main(String[] args) { } private int currentpage; // 当前页数 private

CLHep 2.1.1.0发布 实用工具类

CLHep是一套HEP特定的基础库和实用工具类,如随机生成器,物理向量,几何,和线性代数.CLHep是由一个独立于任何外部的程序包构成,即允许在一定条件下CLHEP的相互依存关系). CLHep 2.1.1.0版本增加了一个Azzalini歪斜正态分布的实施,修复了一些小的bug. 软件信息:http://wwwasd.web.cern.ch/wwwasd/lhc++/clhep/ 下载地址: Source: http://wwwasd.web.cern.ch/wwwasd/lhc++/clhe

翻翻git之---实用工具类Lazy(绝对的好东西,走过路过别错过)

转载请注明出处:这里写链接内容 今天还是继续昨天的从Git上找点"有用的","好玩的","推荐的"东西给大家,今天贴的是一个工具类.地址如下https://github.com/ddwhan0123/Lazy 原作者Blog:http://weibo.com/2675061813/profile?topnav=1&wvr=6 他有一些比较常用的,诸如设备状态啊,土司啊,窗口啊,测量啊什么的,还有些我觉得平时回去搜,但是不多的资源,如拼音和

http接口开发请求参数签名实用工具类

作用: 在http接口对参数做签名,防止接口被非法调用    package com.yanek.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.util.ArrayList; import java

Android封装的http请求实用工具类

复制代码 代码如下:import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.URLEncoder;import java.security.KeyStore;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Map.Entry; import org.apache.http.

ExtJS实用工具类 Ext.util.TaskRunner

TaskRunner 在浏览器提供的 setTimout()/setInterval() 基础上继续完善, 扩展了主要两项功能:执行次数的限制.执行时间的限制(即超时).TaskRunner 旨在利用计时器分时执行方法提供一个相对简易的并行运行机制,其目的不但在于一般的延时执行任务(或者另一个类 DelayedTask 会更合适),还可以同时进行多项任务.这样的话,任意个独立的任务都可以在任何时候开始,并彼此独立地运行.那么是否与多线程的概念有些相近呢?其实不尽然--这里必须说明一下,尽管 Ex

Java Class 映射及实用工具类完整源代码

源代码 package com.elink.util; /* * <p>Company: 凌科软件 www.elingke.com </p> * @author liubaojun * @version 1.0 * Created on 2004-11-29 * 来源于 elinkBSP 部分源代码 */ import java.lang.reflect.*;import java.net.*; public class ClassUtil{ /** @param strClass

POI入门(以及两个实用工具类)

1.HelloPOI 在我们实际的开发中,常常有需要导入导出excel和word的要求,POI便是一个很好的解决方案. Apache的Jakata项目的POI子项目,目前比较成熟的是HSSF接口,处理MSExcel对象.它不象我们仅仅是用csv生成的没有格式的可以由Excel转换的东西,而是真正的Excel对象,你可以控制一些属性如sheet,cell等等. 首先,理解一下一个Excel的文件的组织形式,一个Excel文件对应于一个workbook(HSSFWorkbook),一个workboo