📄 xmlutil.java
字号:
}
/**
* 从Element的下一级中获得指定名称的子Element 集合
* @param Element superEle
* @param String subName
* @return Element
*/
public final static Vector subElementList(Element superEle, String subName) {
Vector v = new Vector();
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)) {
v.add(node);
}
}
}
return v;
}
/**
* 从Element中获得value
* @param Element ele
* @return String
*/
public static String getElementValue(Element ele) {
String value = null;
if (ele == null)
return null;
else {
Node node = ele.getFirstChild();
if (node == null) {
return null;
} else {
value = node.getNodeValue();
if (value != null) {
value = value.trim();
}
return value;
}
}
}
/**查找子节点
*
* @param element
* @param name
* @return
*/
public static Element find(Element element, String name) {
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
if (child instanceof Element && child.getNodeName().equals(name))
return (Element) child;
}
return null;
}
public static Element findGrandson(Element element, String childName,
String grandsonName) {
Element child = find(element, childName);
if (child == null)
return null;
return find(child, grandsonName);
}
public static String getGrandsonValue(Element element, String childName,
String grandsonName) {
Element grandson = findGrandson(element, childName, grandsonName);
if (grandson == null)
return null;
return getTextValue(grandson);
}
/**
* 返回某个文档节点的XPath( 仅包括各级节点名称 )
*
* @param node
* @return
*/
public static String getPath(Node node) {
String path = "";
Node current = node;
while (current != null && !(current instanceof Document)) {
path = current.getNodeName() + "/" + path;
current = current.getParentNode();
}
if (path != null)
path = path.substring(0, path.lastIndexOf("/"));
return path;
}
/** 删掉仅仅由空格\回车\结束符等构成的TextNode
*
* @param node
* @return Node
*/
private static Node removeSpace(Node node) {
NodeList list = node.getChildNodes();
if (list.getLength() == 1
&& list.item(0).getNodeType() == Node.TEXT_NODE
&& node.getNodeType() == Node.ELEMENT_NODE) {
Text text = (Text) node.getChildNodes().item(0);
text.setData(text.getData().trim());
return node;
}
for (int i = 0; i < list.getLength(); i++) {
Node tmpNode = list.item(i);
if (tmpNode.getNodeType() == Node.TEXT_NODE) {
String str = tmpNode.getNodeValue();
if (XmlUtil.isSpace(str)) {
tmpNode.getParentNode().removeChild(tmpNode);
i--;
}
} else if (tmpNode.getNodeType() == Node.ELEMENT_NODE) {
removeSpace(tmpNode);
}
}
return node;
}
/** 判断字符串里是否有空格
*
* @param String str
* @return boolean
*/
private static boolean isSpace(String str) {
for (int i = 0; i < str.length(); i++) {
for (int j = 0; j < chars.length; j++) {
if (!isSpace(str.charAt(i))) {
return false;
}
}
}
return true;
}
/** 判断字符是否是空格
*
* @param char c
* @return boolean
*/
private static boolean isSpace(char c) {
for (int j = 0; j < chars.length; j++) {
if (chars[j] == c) {
return true;
}
}
return false;
}
/** 从 xml file 中解析一个Document Instance
*
* @param String fileName
* @return Document
*/
public final static Document parseFile(String fileName) {
try {
return parseFileThrowsException(fileName);
} catch (Exception e) {
// Logger.error(DSBCore.getDefault(), e);
}
return null;
}
/** 从 xml file 中解析一个Document Instance, throw Exception
*
* @param fileName
* @return Document
* @throws Exception
*/
public final static Document parseFileThrowsException(String fileName)
throws Exception {
File file = new File(fileName);
FileInputStream is = null;
if (file.exists()) {
is = new FileInputStream(file);
try {
Document document = getXMLBuilder().parse(is);
return document;
} catch (Exception e) {
// Logger.error(DSBCore.getDefault(), e);
} finally {
if (is != null) {
is.close();
}
}
} else
throw new Exception("file " + fileName + " doesn't exist!");
return null;
}
/**
* 从 xml Stream 解析一个Document Instance
* @param InputStream stream
* @return Document
*/
public final static Document parseStream(InputStream stream) {
try {
return getXMLBuilder().parse(stream);
} catch (Exception e) {
}
return null;
}
/** 从 xml file 中解析一个Document Instance, throw Exception
*
* @param fileName
* @return Document
* @throws Exception
*/
public final static Document parseStrings(String source) throws Exception {
if (source != null && source.length() > 1
&& (int) source.charAt(0) == 65279)
source = source.substring(1);
ByteArrayInputStream inputStream = null;
try {
char c = source.charAt(0);
inputStream = new ByteArrayInputStream(source.getBytes("UTF-8"));
Document document = getXMLBuilder().parse(inputStream);
return document;
} catch (Exception e) {
throw e;
} finally {
if (inputStream != null)
inputStream.close();
}
}
/**
* 将 Document 转化为 String, 保存到指定路径的文件中<br>
* 如果文件不存在, 将新建文件, 如果存在, 将覆盖原文件
* @param doc
* @param filePath
* @param isFormat 是否将 document 进行格式化
*/
public static void saveDocument(Document doc, String filePath,
boolean isFormat) throws Exception {
if (doc == null || filePath == null) {
return;
}
filePath = filePath.replace('/', File.separatorChar);
filePath = filePath.replace('\\', File.separatorChar);
String content = null;
content = node2String(doc, isFormat, true);
//避免在win2000中, 如果以前存在一个同名但大小写不一致的文件
//创建出来的文件仍使用原来的文件名
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
file.renameTo(file);
}
} catch (Exception e) {
throw new Exception(e);
}
BufferedReader in = new BufferedReader(new CharArrayReader(content
.toCharArray()));
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath), "UTF-8")); //$NON-NLS-1$
String tmp = in.readLine();
while (true) {
if (tmp == null) {
break;
} else {
writer.write(tmp);
writer.write("\r\n"); //$NON-NLS-1$
writer.flush();
}
tmp = in.readLine();
}
} catch (Exception e) {
// Logger.error(CorePlugin.getDefault(), e);
throw new Exception(e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (Exception e) {
}
}
}
}
public static void saveDocument(Document doc, IFile iFile, boolean isFormat)
throws Exception {
if (doc == null || iFile == null) {
return;
}
String content = null;
try {
content = XmlUtil.node2String(doc, isFormat);
String encoding = System.getProperty("encoding", "UTF-8");
ByteArrayInputStream in = new ByteArrayInputStream(content
.getBytes(encoding));
if (!iFile.exists()) {
iFile.create(in, true, null);
} else {
iFile.setContents(in, true, true, null);
}
} catch (Exception e) {
throw new Exception(e);
}
}
/** 实例化一个DocumentBuilder
*
* @return DocumentBuilder
*/
private final static DocumentBuilder getXMLBuilder() {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
return db;
} catch (ParserConfigurationException e) {
// Logger.error(DSBCore.getDefault(), e);
}
return null;
}
/**
* 获得一个new Document Instance
* @return Document
*/
public final static Document getNewDocument() {
Document doc = getXMLBuilder().newDocument();
return doc;
}
/**
* 设置Attr的值
* @param ele
* @param name
* @param value
*/
public static void setAttrValue(Element ele, String name, Object value) {
if (value == null)
return;
else {
ele.setAttribute(name, value.toString());
}
}
/** 以指定的charset读文件
*
* @param file 文件名
* @param charsetName 指定的charset
* @return 文件内容
* @throws Exception
*/
public static String readFile(File file, String charsetName)
throws Exception {
FileInputStream inputStream = null;
try {
if (file == null || !file.exists())
return null;
inputStream = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, charsetName));
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
buffer.append("\n"); //$NON-NLS-1$
}
return buffer.toString();
} catch (Exception e) {
throw new Exception(e);
} finally {
if (inputStream != null)
inputStream.close();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -