📄 xmlutil.java
字号:
/*******************************************************************************
* $Header: /cvsroot/EOS6/work_dir/niegy/com.primeton.studio.gef.ui/src/com/primeton/studio/gef/ui/util/XmlUtil.java,v 1.2 2006/12/30 02:45:04 niegy Exp $
* $Revision: 1.2 $
* $Date: 2006/12/30 02:45:04 $
*
*==============================================================================
*
* Copyright (c) 2001-2006 Primeton Technologies, Ltd.
* All rights reserved.
*
* Created on 2006-10-30
*******************************************************************************/
package com.primeton.studio.gef.ui.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import org.eclipse.core.resources.IFile;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import com.sun.org.apache.xml.internal.serializer.OutputPropertiesFactory;
import com.sun.org.apache.xml.internal.serializer.Serializer;
import com.sun.org.apache.xml.internal.serializer.SerializerFactory;
import com.sun.org.apache.xpath.internal.XPathAPI;
/**
* TODO此处填写 class 信息
*
* @author niegy (mailto:niegy@primeton.com)
*/
/*
* 修改历史
* $Log: XmlUtil.java,v $
* Revision 1.2 2006/12/30 02:45:04 niegy
* 重构代码
*
* Revision 1.1 2006/11/17 03:15:13 niegy
* create
*
*/
public class XmlUtil {
private static final String DEFAULT_XML_ENCODING = "UTF-8";
//space符号
private static char[] chars = { 'n', (char) 9, (char) 10, (char) 13, ' ' };
/** 实例化XML Document
*
* @return Document
*/
public static Document newDocument() {
return getXMLBuilder().newDocument();
}
/** 给指定父节点创建子节点(父节点是Document的情况)
*
* @param Document parent
* @param String name
* @return Element
*/
public static Element createElement(Document document, String name) {
Element element = document.createElement(name);
document.appendChild(element);
return element;
}
/** 给指定父节点创建子节点(父节点是Element的情况)
*
* @param Element parent
* @param String name
* @return Element
*/
public static Element createElement(Element parent, String name) {
return createField(parent, name, null);
}
/** 给指定父节点创建子节点并赋值
*
* @param NodeElement parent
* @param String name
* @param String value
* @return Element
*/
public static Element createField(Element parent, String name, String value) {
Document document = parent.getOwnerDocument();
if (document == null)
return null;
//Creates an element of the type specified
Element element = document.createElement(name);
//Adds the node newChild to the end of the list of children of this node
parent.appendChild(element);
if (value != null && !value.equals("")) {
//Creates a Text node given the specified string
Text text = document.createTextNode(value);
element.appendChild(text);
}
return element;
}
/** 取得指定元素的指定节点的值
*
* @param Element element
* @param String name
* @return String
*/
public static String getFieldValue(Element element, String name) {
if (element == null || name == null || name.equals(""))
return null;
//get the NodeList that contains all children of this node
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node field = children.item(i);
if (field instanceof Element && field.getNodeName().equals(name)) {
return getTextValue(field);
}
}
return null;
}
/** 取得指定子元素
*
* @param Element element
* @param String fieldName
* @return Element
*/
public static Element getChild(Element element, String fieldName) {
if (element == null || fieldName == null || fieldName.equals(""))
return null;
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element
&& child.getNodeName().equals(fieldName)) {
return (Element) child;
}
}
return null;
}
/** 取得节点的TextValue
*
* @param NodeElement node
* @return String
*/
public static String getTextValue(Node node) {
NodeList children = node.getChildNodes();
if (children == null)
return ""; //$NON-NLS-1$
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE) {
String value = ((org.w3c.dom.Text) child).getNodeValue();
if (value != null)
value = value.trim();
return value;
}
}
return ""; //$NON-NLS-1$
}
/** 设置元素属性
*
* @param Element element
* @param String name
* @param String value
*/
public static void setAttribute(Element element, String name, String value) {
if (element == null || value == null || value.equals(""))
return;
element.setAttribute(name, value.trim());
}
/**
* convert the node to string, 默认不进行格式化
* @param node a node
* @return the result string
*/
public final static String node2String(Node node) {
return node2String(node, false);
}
/**
* convert the node to string<br>
* 格式化输出将改变node的结构
* @param node a node
* @param isFormat true:格式化输出
* @return the result string
*/
public final static String node2String(Node node, boolean isFormat) {
return node2String(node, isFormat, true);
}
/** 将XML节点序列化成字符串
*
* @param node
* @param isFormat
* @param hasHead
* @return
*/
public final static String node2String(Node node, boolean isFormat,
boolean hasHead) {
if (node == null)
return null;
//The node is a Document
if (node.getNodeType() == Node.DOCUMENT_NODE)
node = ((Document) node).getDocumentElement();
CharArrayWriter writer = new CharArrayWriter();
try {
Properties prop = OutputPropertiesFactory
.getDefaultMethodProperties("xml");
prop.setProperty("encoding", DEFAULT_XML_ENCODING);
Serializer serializer = SerializerFactory.getSerializer(prop);
if (isFormat) {
prop.setProperty(OutputKeys.INDENT, "yes");
prop.setProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "4");
XmlUtil.removeSpace(node);
} else {
prop.setProperty(OutputKeys.INDENT, "no");
}
serializer.setOutputFormat(prop);
serializer.setWriter(writer);
//串行化输出结果
serializer.asDOMSerializer().serialize(node);
String str = new String(writer.toCharArray());
if (hasHead) {
if (!str.startsWith("<?xml")) {
str = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
.concat(str);
}
return str;
} else {
if (!str.startsWith("<?xml")) {
return str;
}
int op = str.indexOf("?>");
str = str.substring(op + "?>".length()).trim();
if (str.startsWith("\n")) {
str = str.substring(1);
}
}
} catch (Exception e) {
// Logger.error(DSBCore.getDefault(), e);
}
return node.toString();
}
/**
* find node array from node use by the given XPath
* @param node a node
* @param xql XPath
* @return the node array, if not find return null
* @throws XmlUtilException
*/
public final static NodeList findNodes(Node node, String xql)
throws XmlUtilException {
if ((xql == null) || (xql.length() == 0)) {
throw new XmlUtilException("xql == null");
}
if (node == null) {
throw new XmlUtilException("Node == null");
}
try {
if (node.getNodeType() != Node.DOCUMENT_NODE)
xql = processXql(xql);
return XPathAPI.selectNodeList(node, xql);
// NodeList findNode = XPathAPI.selectNodeList(node, xql);
// if(findNode == null || findNode.getLength() == 0){
// if(!"bendpoints/bendpoint".equals(xql)){
// String root = null;
// if(node.getNodeType() == Node.DOCUMENT_NODE){
// root = ((Document)node).getDocumentElement().toString();
// }else{
// root = node.toString();
// }
// Logger.debug(CorePlugin.getDefault(), "findNodes not find : [" + xql + "]\n" + root);
// }
// }
// return findNode;
} catch (Exception te) {
throw new XmlUtilException(te.getMessage());
}
}
/**
* find a single node from node use by the given XPath
* @param node a node
* @param xql XPath
* @return the node, if not find return null
* @throws XmlUtilException
*/
public final static Node findNode(Node node, String xql)
throws XmlUtilException {
if ((xql == null) || (xql.length() == 0)) {
throw new XmlUtilException("xql == null");
}
if (node == null) {
throw new XmlUtilException("Source node == null");
}
try {
if (node.getNodeType() != Node.DOCUMENT_NODE)
xql = processXql(xql);
return XPathAPI.selectSingleNode(node, xql);
// Node findNode = XPathAPI.selectSingleNode(node, xql);
// if(findNode == null && !"bendpoints/bendpoint".equals(xql)){
// String root = null;
// if(node.getNodeType() == Node.DOCUMENT_NODE){
// root = ((Document)node).getDocumentElement().toString();
// }else{
// root = node.toString();
// }
// Logger.debug(CorePlugin.getDefault(), "findNode not find : [" + xql + "]\n" + root);
// }
// return findNode;
} catch (Exception te) {
throw new XmlUtilException(te.getMessage());
}
}
private final static String processXql(String xql) {
if (xql.length() > 1 && xql.charAt(0) == '/')
xql = ".".concat(xql);
return xql;
}
/**
* 从Element的下一级中获得指定名称子Element的Value, 如果重名, 得到第一个
* @param Element superEle
* @param String subName
* @return Element
*/
public final static String subElementValue(Element superEle, String subName) {
Element element = subElement(superEle, subName);
if (element == null)
return null;
else {
return getElementValue(element);
}
}
/**
* 从Element的下一级中获得指定名称的子Element
* 如果重名, 得到第一个
* @param Element superEle
* @param String subName
* @return Element
*/
public final static Element subElement(Element superEle, String subName) {
NodeList list = superEle.getChildNodes();
if (list == null)
return null;
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
if (node.getNodeName().equals(subName)) {
return (Element) node;
}
}
}
return null;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -