⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlutil.java

📁 java系统通用框架 很实用的东东 一般人都看的懂,
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*****************************************************************************
* (C) Copyright 2004 。
* 保留对所有使用、复制、修改和发布整个软件和相关文档的权利。
* 本计算机程序受著作权法和国际公约的保护,未经授权擅自复制或
* 传播本程序的全部或部分,可能受到严厉的民事和刑事制裁,并
* 在法律允许的范围内受到最大可能的起诉。
*/

 /*****************************************************************************
  * @作者:Golden Peng
  * @版本: 1.0
  * @时间: 2002-10-08
  */
 /*****************************************************************************
  * 修改记录清单
  * 修改人  :
  * 修改记录:
  * 修改时间:
  * 修改描述:
  *
  */
package com.corp.bisc.ebiz.util;

/**
 * Insert the type's description here.
 * Creation date: (9/18/00 4:33:59 PM)
 * @author: Administrator
 */
import java.io.*;
import java.util.*;

import org.w3c.dom.*;
import com.ibm.xml.parsers.*;
import org.xml.sax.InputSource;
//
import javax.servlet.http.*;

public class XMLUtil {
	public static final int STRING = 0;
	public static final int SHORT = 1;
	public static final int INT = 2;
	public static final int INTEGER = 2;
	public static final int LONG = 3;
	public static final int FLOAT = 4;
	public static final int DOUBLE = 5;
	public static final int CHAR = 6;
	public static final int BOOLEAN = 7;
	public static final int CALENDAR = 8;
	public static Hashtable xmlChars;
	static{
		xmlChars = new Hashtable();
		xmlChars.put( ">", ">" );
		xmlChars.put( "<", "&lt;" );
		xmlChars.put( "&", "&amp;" );
		xmlChars.put( "'", "&apos;" );
		xmlChars.put( "\"", "&quot;" );
	}
/**
 * XMLUtil constructor comment.
 */
public XMLUtil() {
	super();
}
public static String char2XMLString(char ch) {
	String temp = new String(new char[] {ch});
	if (xmlChars.containsKey(temp)) {
		temp = (String) xmlChars.get(temp);
	}
	return temp;
}
protected static String getNodeTextValue(Node node) {
	String value = null;
	if (node != null) {
		switch (node.getNodeType()) {
			case Node.ELEMENT_NODE :
				Node child = node.getFirstChild();
				if (child == null) {
					value = "";
				}
				else if ("#text".equals(child.getNodeName())) {
					value = child.getNodeValue();
				}
				break;
			case Node.ATTRIBUTE_NODE :
				value = node.getNodeValue();
				break;
			default :
				break;
		}
	}
	return value;

}
	/**
 * Insert the method's description here.
 * Creation date: (2/6/2000 8:56:03 PM)
 * @return int
 * @param pattern java.lang.String
 */
public static int getSepPos(String pattern) {
	// find the first delimitor
	// exluding those in "": a["/as"]/b
	//
	// very weakly, assuming pattern name never starts with "/"
	//
	StringTokenizer st = new StringTokenizer(pattern, "\"");
	int sepPos = -1;
	for (int d = 0, curPos = 0; st.hasMoreElements(); d = ((d == 0) ? 1 : 0)) {
		// seach those in odd sections
		String s = st.nextToken();
		if (d == 0) {
			int p = s.indexOf("/");
			if (p >= 0) {
				sepPos = curPos + p;
				break;
			}
		}
		curPos += s.length() + 1; // 1 for the length of ".
	}
	return sepPos;
}
/**
 * Replace <>& with HTML safe entities
 * Creation date: (28/04/2000 4:02:10 PM)
 * @return java.lang.String
 * @param xml java.lang.String
 */
public static String htmlEscape(String xml) {
	if (xml == null) return null;
	String ret = xml;
	StringBuffer sb = new StringBuffer();
	// do & first
	int p, q;
	for(q = ret.indexOf("&"), p = 0; q >= 0; p = ++q, q = ret.indexOf("&", p)) {
		sb.append(ret.substring(p, q));
		sb.append("&amp;");
	}
	sb.append(ret.substring(p));
	ret = sb.toString();
	sb = new StringBuffer();
	// do <
	for(q = ret.indexOf("<"), p = 0; q >= 0; p = ++q, q = ret.indexOf("<", p)) {
		sb.append(ret.substring(p, q));
		sb.append("&lt;");
	}
	sb.append(ret.substring(p));
	ret = sb.toString();
	sb = new StringBuffer();
	// do >
	for(q = ret.indexOf(">"), p = 0; q >= 0; p = ++q, q = ret.indexOf(">", p)) {
		sb.append(ret.substring(p, q));
		sb.append("&gt;");
	}
	sb.append(ret.substring(p));
	ret = sb.toString();
	return ret;
}
/**
 * All the names starting with "_" are ignored!
 * Creation date: (1/31/2000 2:10:05 AM)
 * @return java.lang.String
 * @param enum java.util.Enumeration
 */
public static String httpReq2XML(HttpServletRequest req) {
	StringBuffer buf = new StringBuffer("<?xml version=\"1.0\" ?><args>");
	Enumeration e = req.getParameterNames();
	if (e.hasMoreElements()) {
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			if (!name.startsWith("_")) {
				String vals[] = (String[]) req.getParameterValues(name);
				if (vals != null) {
					for (int i = 0; i < vals.length; i++) {
						buf.append("<" + name + ">" + stringToXMLString( vals[i] )+ "</" + name + ">");
						}
				}
			}
		}
	}
	buf.append("</args>");
	return buf.toString();
}
/**
 * Insert the method's description here.
 * Creation date: (2/6/2000 7:01:48 PM)
 * @param args java.lang.String[]
 */
public static void main(String[] args) {
	try {
/*
		Document doc = null;
		DOMParser parser = new DOMParser();
		parser.parse("e:/IBMVJava/ide/project_resources/IBM WebSphere Test Environment/WebGate.xml");
		doc = parser.getDocument();
		if (doc == null) {
			System.err.println("null doc?");
			throw new Exception("Could not get/parse the webgate.xml.");
		} else {
			//Node n = XMLUtil.selectSingleNode(doc.getDocumentElement(), "webapp/views/page[@id=\"/services.jsp\"]/events/event[@name=\"intermodal\"]");
			Node n = XMLUtil.selectSingleNode2(doc, "webapp/views/page[@id=\"/services.jsp\"]/events/event[@name=\"intermodal\"]");
			if (n != null) {
				XMLUtil.printDOMTree(n);
			} else {
				System.out.println("Not found!");
			}

			Vector v = XMLUtil.selectNodes2(doc, "webapp/views/page[@id=\"/services.jsp\"]/events/event[@name=\"intermodal\"]");
			System.out.println("# of item found: " + v.size());
		}
*/
	String xml = "<a><b>hello</b><c>sdfsdfds</c></a>";
	Document doc = XMLUtil.string2Dom(xml);
	Node n = doc.getDocumentElement();
	String v = XMLUtil.selectSingleValue2(n, "c");
	System.out.println(v);
} catch (Exception e) {
		System.out.println("exception: " + e);
		e.printStackTrace();
	}
}
/**
 * single token match: no nested structure.
 * Creation date: (2/7/2000 11:28:16 PM)
 * @return boolean
 * @param node org.w3c.dom.Node
 * @param pattern java.lang.String
 */
public static boolean matchCurrentNode(Node node, String pattern) {
	boolean ret = false;
	//
	// TODO: add special processing for : "./", "/...", "../../", etc...
	//
	String curTK = pattern.trim();

	//
	// basic format check
	// attr can only be the last token if an attr is on the path
	if (pattern.trim().endsWith("/") || pattern.indexOf("@") == 0 && pattern.indexOf("/") > 0) {
		// better to throw expcetion...
		return false;
	}
	String curName = null;
	String attr = null;
	String attrVal = null;
	String operator = "?"; // "=", "!=", "?" - existance, default
	// check condition, [@att="...."] for now

	// parsing, regexp will help...
	int p = curTK.indexOf("[");
	if (p >= 0) {
		curName = curTK.substring(0, p).trim();
		String cond = curTK.substring(p + 1, curTK.indexOf("]")).trim();
		if (cond.indexOf("@") == 0) {
			if (cond.indexOf("=") > 1) { // value comparison. "=" and "!=", for now
				if (cond.indexOf("!=") > 1) { // NE
					operator = "!=";
				} else {
					operator = "=";
				}
				attr = cond.substring(cond.indexOf("@") + 1, cond.indexOf(operator)).trim();
				attrVal = cond.substring(cond.indexOf(operator) + operator.length()).replace('"', ' ').trim();
			} else { // test existence only
				operator = "?";
				attr = cond.substring(cond.indexOf("@") + 1).trim();
			}
		} else { // it's not attr related condition
			; // to be implemented
		}
	} else {
		curName = curTK;
	}

	// --------------------- preparation work is done-------
	// try matching current level
	//

	// find out if the current token is for an element or an attribute
	if (curName.indexOf("@") == 0) { // find attr
		if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
			String att2Match = curName.substring(1);
			if (att2Match.equals(node.getNodeName())) {
				ret = true;
			}
			// ignore the rest of the token
		}
	} else { // match an element
		if (".".equals(curName)) {
				// . always match the current node
			ret = true;
		} else {
			if (curName.equals(node.getNodeName())) {
				boolean match = false;
				if (attr != null && node.getNodeType() == Node.ELEMENT_NODE) {
					if (operator.equals("=")) {
						if (attrVal.equals(((Element) node).getAttribute(attr))) {
							match = true;
						}
					} else {
						if (operator.equals("!=")) {
							if (!attrVal.equals(((Element) node).getAttribute(attr))) {
								match = true;
							}
						} else { // existance only
							if (((Element) node).getAttributeNode(attr) != null) {
								match = true;
							}
						}
					}
				} else { // no extra condition
					match = true;
				}
				if (match) {
					ret = true;
				} else {
					ret = false;
				}
			} else {
				ret = false;
			}
		}
	}
	return ret;
}
/** Prints the specified node, then prints all of its children. */
public static String Node2HtmlString(Node node) {
	if (node == null) {
		return null;
	}
//
	StringWriter sw = new StringWriter();
	printDOMTreeHtmlSafe(new PrintWriter(sw), node);
	return sw.toString();
}
/** Prints the specified node, then prints all of its children. */
public static String Node2String(Node node) {
	if (node == null) {
		return null;
	}
//
	StringWriter sw = new StringWriter();
	printDOMTree(new PrintWriter(sw), node);
	return sw.toString();
}
	private void print (PrintWriter out, String name, int value) {
		out.print(" " + name + ": ");
		if(value == -1) {
			out.println("&lt;none&gt;");
		}
		else {
			out.println(value);
		}
	}
	private void print (PrintWriter out, String name, String value) {
		out.print(" " + name + ": ");
		out.println(value == null ? "&lt;none&gt;" : value);
	}
/** Prints the specified node, then prints all of its children. */
public static void printDOMTree(PrintWriter out, Node node) {
	if (node == null) {
		out.println("printDOMTree - null node!");
		return;
	}
	//
	int type = node.getNodeType();
	switch (type) {
		// print the document element
		case Node.DOCUMENT_NODE :
			{
				out.println("<?xml version=\"1.0\" ?>");
				printDOMTree(out, ((Document) node).getDocumentElement());
				break;
			}
			// print element with attributes
		case Node.ELEMENT_NODE :
			{
				out.print("<");
				out.print(node.getNodeName());
				NamedNodeMap attrs = node.getAttributes();
				for (int i = 0; i < attrs.getLength(); i++) {
					Node attr = attrs.item(i);
					out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
				}
				out.println(">");
				NodeList children = node.getChildNodes();
				if (children != null) {
					int len = children.getLength();
					for (int i = 0; i < len; i++)
						printDOMTree(out, children.item(i));
				}
				break;
			}
			// handle entity reference nodes
		case Node.ENTITY_REFERENCE_NODE :
			{
				out.print("&");
				out.print(node.getNodeName());
				out.print(";");
				break;
			}
			// print cdata sections
		case Node.CDATA_SECTION_NODE :
			{
				out.print("<![CDATA[");
				out.print(node.getNodeValue());
				out.print("]]>");
				break;
			}
			// print text.
		case Node.TEXT_NODE :
			{
				out.print(node.getNodeValue());
				break;
			}
			// print processing instruction
		case Node.PROCESSING_INSTRUCTION_NODE :
			{
				out.print("<?");
				out.print(node.getNodeName());
				String data = node.getNodeValue();
				{
					out.print("");
					out.print(data);
				}
				out.print("?>");
				break;
			}
	}
	if (type == Node.ELEMENT_NODE) {
		out.println();
		out.print("</");
		out.print(node.getNodeName());
		out.print('>');
	}
}
/** Prints the specified node, then prints all of its children. */
public static void printDOMTree(Node node) {
	if (node == null) {
		System.out.println("printDOMTree - null node!");
		return;
	}
	//
	int type = node.getNodeType();
	switch (type) {
		// print the document element
		case Node.DOCUMENT_NODE :
			{
				System.out.println("<?xml version=\"1.0\" ?>");
				printDOMTree(((Document) node).getDocumentElement());
				break;
			}
			// print element with attributes
		case Node.ELEMENT_NODE :
			{
				System.out.print("<");
				System.out.print(node.getNodeName());
				NamedNodeMap attrs = node.getAttributes();
				for (int i = 0; i < attrs.getLength(); i++) {
					Node attr = attrs.item(i);
					System.out.print(" " + attr.getNodeName() + "=\"" + attr.getNodeValue() + "\"");
				}
				System.out.println(">");
				NodeList children = node.getChildNodes();
				if (children != null) {
					int len = children.getLength();
					for (int i = 0; i < len; i++)
						printDOMTree(children.item(i));
				}
				break;
			}
			// handle entity reference nodes
		case Node.ENTITY_REFERENCE_NODE :
			{
				System.out.print("&");
				System.out.print(node.getNodeName());
				System.out.print(";");
				break;
			}
			// print cdata sections
		case Node.CDATA_SECTION_NODE :
			{
				System.out.print("<![CDATA[");
				System.out.print(node.getNodeValue());
				System.out.print("]]>");
				break;
			}
			// print text.
		case Node.TEXT_NODE :
			{
				System.out.print(node.getNodeValue());
				break;
			}
			// print processing instruction
		case Node.PROCESSING_INSTRUCTION_NODE :
			{
				System.out.print("<?");
				System.out.print(node.getNodeName());
				String data = node.getNodeValue();
				{
					System.out.print("");
					System.out.print(data);
				}
				System.out.print("?>");
				break;
			}

⌨️ 快捷键说明

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