答案:/**
* helper方法,查找一个指定的元素
*
* @param name 元素名称,格式为 X.Y.Z
* @return Element 如果找到就返回这个元素,否则返回null
*/
public Element findOnly(String name)
{
//分解元素的名称
String[] propName = parsePropertyName(name);
Element element = this.doc.getRootElement();
//遍历搜索匹配的元素
for (int i = 0; i < propName.length; i++)
{
element = element.getChild(propName[i]);
if(element == null) return null;
}
//找到啦!
return element;
}
/**
* Saves the properties to disk as an XML document. A temporary file is
* used during the writing process for maximum safety.
*/
public synchronized void saveProperties() {
OutputStream out = null;
boolean error = false;
// Write data out to a temporary file first.
File tempFile = null;
try {
tempFile = new File(file.getParentFile(), file.getName() + ".tmp");
// Use JDOM's XMLOutputter to do the writing and formatting. The
// file should always come out pretty-printed.
//增加此行使得支持中文 wyl 20021015
XMLOutputter outputter = new XMLOutputter("", true,"GB2312");
out = new BufferedOutputStream(new FileOutputStream(tempFile));
//增加此行,使得xml文件没有空行。 wyl 20021030
outputter.setTextNormalize(true);
outputter.output(doc, out);
}
catch (Exception e) {
e.printStackTrace();
// There were errors so abort replacing the old property file.
error = true;
}
finally {
try { out.close(); }
catch (Exception e) {
e.printStackTrace();
error = true;
}
}
// No errors occured, so we should be safe in replacing the old
if (!error) {
// Delete the old file so we can replace it.
if (!file.delete()) {
System.err.println("Error deleting property file: " +
file.getAbsolutePath());
return;
}
// Rename the temp file. The delete and rename won't be an
// automic operation, but we should be pretty safe in general.
// At the very least, the temp file should remain in some form.
if (!tempFile.renameTo(file)) {
System.err.println("Error renaming temp file from " +
tempFile.getAbsolutePath() + " to " + file.getAbsolutePath());
}
}
}
/**
* Returns an array representation of the given crm property. crm
* properties are always in the format "prop.name.is.this" which would be
* represented as an array of four Strings.
*
* @param name the name of the crm property.
* @return an array representation of the given crm property.
*/
public String[] parsePropertyName(String name) {
// Figure out the number of parts of the name (this becomes the size
// of the resulting array).
int size = 1;
for (int i=0; i<name.length(); i++) {
if (name.charAt(i) == '.') {
size++;
}
}
String[] propName = new String[size];
// Use a StringTokenizer to tokenize the property name.
StringTokenizer tokenizer = new StringTokenizer(name, ".");
int i = 0;
上一个:对xml文件的回写(一)
下一个:搜集整理的对xml文件操作的java程序,基本可以满足基本的操作。