廢話不多說,直接上代碼及說明吧!
package Dao;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class ReadXML {
private String fileName;
public ReadXML(String fileName)
{
this.fileName = fileName; //構造函數,直接将需要讀取的fileName通過函數初始化進行傳值,當然你也可以使用其他方法!
}
public List redaXml()
{
ArrayList elementRefArray = new ArrayList(); //這是一個ArrayList 容器,用于存儲多出來的資訊
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(new File(this.fileName));
NodeList nodes = doc.getElementsByTagName("elementName"); //從xml檔案中讀出名為elementName的節點,放在nodes中,假如你的xml有很多這個節點,都會被存下來
for (int i = 0; i < nodes.getLength(); i++)
{
Element ele = (Element)nodes.item(i); //Element 是将節點變為元素具體我還有點亂,YYYY
其中name 為node 的屬性,XXXX為node屬性為name的值,而YYYY為node節點的值(不知小弟說法是否正确,不過和上面對應正确··)
Ok 搞好解析XML後,大多數情況下,我們需要對其值進行操作,是以上面的代碼我把它放在一個ArrayList中,友善後續操作。操作好後,可能你又需要進行檔案儲存,是以下面的代碼是檔案儲存的一種方法。。。
private static String path = "D:/loadReplace.js"; // 檔案儲存路徑和名稱
private static File filename = new File(path);
public creat() throws IOException
{
RandomAccessFile ss = null;
String str = "把我寫進去!";
if (!filename.exists()) {
filename.createNewFile(); //建立檔案
try {
ss= new RandomAccessFile(filename, "rw");
ss.writeBytes(str); //寫檔案
} catch (IOException e1) {
// TODO 自動生成 catch 塊
e1.printStackTrace();
} finally {
if (ss!= null) {
try {
ss.close(); //關閉檔案
System.out.println("建立結束");
} catch (IOException e2) {
// TODO 自動生成 catch 塊
e2.printStackTrace();
}
}
}
}