xmlutil.java

来自「很好的WebSphereCE轻量级J2EE服务器使用入门的范例程序」· Java 代码 · 共 108 行

JAVA
108
字号
package com.ibm.db2.simplej2ee;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.ibm.db2.jcc.DB2Xml;

public class XmlUtil
{
	/*
	 * DOMImplementation used for creating Document objects.
	 */
	private DocumentBuilder docBuilder = null;
	
	/*
	 * DocumentBuilder used for parsing Document objects.
	 */
	private DOMImplementation domImpl = null;
	
	public XmlUtil() throws ParserConfigurationException
	{
		docBuilder = DocumentBuilderFactory.newInstance()
			.newDocumentBuilder();
		domImpl = docBuilder.getDOMImplementation();
	}
	
	/*
	 * Print XML document to pw.
	 */
	public void printDoc(Element root, PrintWriter pw)
	{
		OutputFormat outFormat = new OutputFormat("XML", "UTF-8", true);
		outFormat.setIndent(1);
		outFormat.setIndenting(true);
		
		XMLSerializer xmlSer = new XMLSerializer();
		xmlSer.setOutputCharStream(pw);
		xmlSer.setOutputFormat(outFormat);
		
		try
		{
			xmlSer.asDOMSerializer();
			xmlSer.serialize(root);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	
	/*
	 * @returns A Document object from a DB2Xml object or null
	 * if the DB2Xml object is null.
	 */
	public Document db2XmlToDocument(DB2Xml db2xml)
	{
		if (db2xml == null)
			return null;
		
		try
		{
			return docBuilder.parse(db2xml.getDB2BinaryStream());
		}
		catch (SAXException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		catch (SQLException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/*
	 * Create a Document object using 'rootElementName' as the root
	 * element's name of the document.
	 */
	public Document createDocument(String rootElementName)
	{
		return domImpl.createDocument("http://www.w3.org/2001/XMLSchema",
				rootElementName, null);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?