XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard Generalized Markup Language,标准通用标记语言)。
正由于XML结构简单被广泛用来作为跨平台之间交互数据的形式,主要针对数据的内容,通过不同的格式化描述手段(XSLT,CSS等)可以完成最终的形式表达(生成对应的HTML,PDF或者其他的文件格式)。
所以我们就可以用music.xml来存放歌曲列表和歌曲信息。
读取xml文件
public class xmlReadTest {
Document doc ;
int num;
public xmlReadTest(String filename){
long lasting = System.currentTimeMillis();
try {
File file = new File(filename);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = (Document) builder.parse(file);
NodeList nl = doc.getElementsByTagName("SONG");
num=nl.getLength();
for (int i = 0; i < nl.getLength(); i++) {
System.out.print("歌曲 :" + doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue());
System.out.println("路径 :" + doc.getElementsByTagName("mp3File").item(i).getFirstChild().getNodeValue());
System.out.println("运行时间:" + (System.currentTimeMillis() - lasting) + "毫秒");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String getTitle(int i){
return doc.getElementsByTagName("title").item(i).getFirstChild().getNodeValue();
}
public String getMp3File(int i){
return doc.getElementsByTagName("mp3File").item(i).getFirstChild().getNodeValue();
}
public int getNum(){
return num;
}
}
public class xmlWriteTest {
DocumentBuilderFactory dbf;
DocumentBuilder db ;
Document doc ;
Element root;
OutputStreamWriter osw;
FileOutputStream fos ;
String FileName;
public xmlWriteTest(String filename){
FileName=filename;
dbf = DocumentBuilderFactory.newInstance();
db = null;
try {
db = dbf.newDocumentBuilder();
} catch (Exception e) {
e.printStackTrace();
}
doc = db.newDocument();
root = doc.createElement("RESULT");
doc.appendChild(root);
try {
fos = new FileOutputStream(filename);
osw = new OutputStreamWriter(fos);
((XmlDocument) doc).write(osw, "gb2312");
osw.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void addNewSong(String t,String mF){
Element song = doc.createElement("SONG");
Element title = doc.createElement("title");
Text tTitle = doc.createTextNode(t);
title.appendChild(tTitle);
song.appendChild(title);
Element file = doc.createElement("mp3File");
Text tFile = doc.createTextNode(mF);
file.appendChild(tFile);
song.appendChild(file);
root.appendChild(song);
try {
fos = new FileOutputStream(FileName);
osw = new OutputStreamWriter(fos);
((XmlDocument) doc).write(osw, "utf-8");
osw.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}